<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Scriptble.com</title>
	<atom:link href="http://scriptble.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://scriptble.com</link>
	<description>{ js : performance }</description>
	<lastBuildDate>Sun, 06 Jan 2013 00:02:56 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Constantly &#8220;Connecting&#8221; in FireFox</title>
		<link>http://scriptble.com/2012/02/20/constantly-connecting-in-firefox/</link>
		<comments>http://scriptble.com/2012/02/20/constantly-connecting-in-firefox/#comments</comments>
		<pubDate>Mon, 20 Feb 2012 08:01:24 +0000</pubDate>
		<dc:creator>jcfant</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=246</guid>
		<description><![CDATA[This is an interesting issue, sometimes we see in FireFox 9 and above an issue where the tab title will actually get set to a state where it says &#8220;Connecting&#8221; and the spinner is constantly in motion. One of the things I found recently when I discovered this was quickly writing out DOM elements and [...]]]></description>
				<content:encoded><![CDATA[<p>This is an interesting issue, sometimes we see in FireFox 9 and above an issue where the tab title will actually get set to a state where it says &#8220;Connecting&#8221; and the spinner is constantly in motion.</p>
<p>One of the things I found recently when I discovered this was quickly writing out DOM elements and then Removing them.</p>
<p><span id="more-246"></span></p>
<h2>Example</h2>
<p>Take the following code, it appends a Node element to the DOM. As soon as the onload or onerror function is fired it removes the element.</p>
<pre class="language-javascript">
var urls = [
...
];

for (var i = 0; i <= urls.length; i++){
	addObjectElement(url);
}

function addObjectElement(url){
	var obj = document.createElement("object");
	obj.data = url;
	
	obj.onload = obj.onerror = function() { removeElement(obj) };
	
	document.appendChild(obj);	
}

function removeElement(item) {
	var parent = item.parentElement;
	p.removeChild(item);
}
</pre>
<p>The previous could would end up causing an issue where FireFox would actually think it was still working. Thus creating the "Connecting" issue and the spinning icon.</p>
<h2>How do we fix it?</h2>
<p>Well, actually the fix is simple. If you wait a small amount of time to actually do the removal, firefox will unlock the thread rendering it back to the being normal.</p>
<p>Let's take a look.</p>
<h2>The fix</h2>
<pre class="language-javascript">
var urls = [
...
];

for (var i = 0; i <= urls.length; i++){
	addObjectElement(url);
}

function addObjectElement(url){
	var obj = document.createElement("object");
	obj.data = url;
	
	obj.onload = obj.onerror = function() { setTimeout(function(){ removeElement(obj)}, 5); };
	
	document.appendChild(obj);	
}

function removeElement(item) {
	var parent = item.parentElement();
	p.removeChild(item);
}
</pre>
<p>Once we add the setTimeout to the code, even at a small 5ms delay, we unlock the thread and cause firefox to resume normal operation.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2012/02/20/constantly-connecting-in-firefox/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How to create and write to an iframe without jQuery</title>
		<link>http://scriptble.com/2012/02/15/how-to-create-and-write-to-an-iframe-without-jquery/</link>
		<comments>http://scriptble.com/2012/02/15/how-to-create-and-write-to-an-iframe-without-jquery/#comments</comments>
		<pubDate>Wed, 15 Feb 2012 19:39:18 +0000</pubDate>
		<dc:creator>jcfant</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=242</guid>
		<description><![CDATA[Recently, I had an issue where I was trying to figure out how to create an iframe, and then append some items into it. Well, it turns out to not be nearly as complicated as I thought. Create the iframe We need to create the iframe without using a src. This way the browser won&#8217;t [...]]]></description>
				<content:encoded><![CDATA[<p>Recently, I had an issue where I was trying to figure out how to create an iframe, and then append some items into it. Well, it turns out to not be nearly as complicated as I thought.</p>
<p><span id="more-242"></span></p>
<h2>Create the iframe</h2>
<p>We need to create the iframe without using a src. This way the browser won&#8217;t try to load anything into the frame itself.</p>
<pre class="language-javascript">
	var docElem = window.document;
	var iframe = doc.createElement("iframe");
	iframe.height = iframe.width = 0;
	docElem.appendChild(iframe);
</pre>
<p>Notice we created a 0x0px iframe that we appended to the DOM<br />
<h2>Add some content</h2>
<p>Now, we just need to add some items to the newly created iframe.</p>
<pre class="language-javascript">
	iframe.document.appendChild(obj);
</pre>
<p>Hmm, that isn&#8217;t working properly in all browsers. Well it turns out, first you need to actually get the proper content window for the iframe before we write to it.</p>
<h2>Getting the proper content window to write to an iframe</h2>
<pre class="language-javascript">
	if (iframe.contentWindow){
	        iframe = iframe.contentWindow;
	}else{
	        if (iframe.contentDocument &#038;&#038; iframe.contentDocument.document){
	                iframe = iframe.contentDocument.document;
	        }else{
	                iframe = iframe.contentDocument;
	        }
	}
</pre>
<p>Now that we actually have the proper context to be able to write to the iframe, lets take a look at how to do it.</p>
<h2>Properly writing to an iframe</h2>
<pre class="language-javascript">
var img = document.createElement("img");
img.src = "someurl.jpg";
iframe.document.open();
iframe.document.appendChild(obj);
iframe.document.close();
</pre>
<h2>Putting it all together in one place</h2>
<p>Here is the full code in one place to see how it works</p>
<pre class="language-javascript">
	var docElem = window.document;
	var iframe = doc.createElement("iframe");
	iframe.height = iframe.width = 0;
	docElem.appendChild(iframe);

	if (iframe.contentWindow){
	        iframe = iframe.contentWindow;
	}else{
	        if (iframe.contentDocument &#038;&#038; iframe.contentDocument.document){
	                iframe = iframe.contentDocument.document;
	        }else{
	                iframe = iframe.contentDocument;
	        }
	}

	var img = document.createElement("img");
	img.src = "someurl.jpg";
	iframe.document.open();
	iframe.document.appendChild(obj);
	iframe.document.close();
</pre>
<h2>Summary</h2>
<p>Why would you use a hidden iframe to show an image? Well, the reason is more about caching items in a browser than actually showing an image. Truth be told, many of the major websites use something similar to cache content for subsequent pages on the site. The technique is different and each browser requires some special logic. But the gist of it remains the same. So the next time you need to create an iframe and write to it, this is the proper techinique.</p>
<ol>
<li>create an iframe</li>
<li>append the iframe to the DOM (otherwise, the iframe element doesn&#8217;t have the proper content window to discover)</li>
<li>detect the content window</li>
<li>open the iframe to writing</li>
<li>write to the iframe</li>
<li>close the iframe</li>
<li>Get Beer!</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2012/02/15/how-to-create-and-write-to-an-iframe-without-jquery/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Removing Debug Statements from Javascript via compiler</title>
		<link>http://scriptble.com/2012/02/01/removing-debug-statements-from-javascript-via-compiler/</link>
		<comments>http://scriptble.com/2012/02/01/removing-debug-statements-from-javascript-via-compiler/#comments</comments>
		<pubDate>Wed, 01 Feb 2012 20:02:54 +0000</pubDate>
		<dc:creator>jcfant</dc:creator>
				<category><![CDATA[Closure]]></category>
		<category><![CDATA[Compilers]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[closure compiler]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=237</guid>
		<description><![CDATA[We all know the pain of getting a bug filed against some of your code and having to dig through it later to find the root cause. Especially, since many times we end up having to add back in all of our debug statements in order to track down the issue. There has to be [...]]]></description>
				<content:encoded><![CDATA[<p>We all know the pain of getting a bug filed against some of your code and having to dig through it later to find the root cause. Especially, since many times we end up having to add back in all of our debug statements in order to track down the issue. There has to be a better way. What if we could write all of our JavaScript with the debug code left in?</p>
<h2>The Better way</h2>
<p>By now, we are all using some compiler to compile your code. Right? If you haven&#8217;t started, grab the <a href="http://closure-compiler.googlecode.com/files/compiler-latest.zip">Closure Compiler</a> to follow through on this example.</p>
<ol>
<li>Download the latest Closure Compiler <a href="http://closure-compiler.googlecode.com/files/compiler-latest.zip">http://closure-compiler.googlecode.com/files/compiler-latest.zip</a></li>
<li>Unzip</li>
<li>Copy the compiler.jar file into your directory with the JS Files.</li>
<li>follow along below and enjoy!</li>
</ol>
<p> If you are using Closure Compiler or Uglify already, you are in luck! Both of these compilers allow you to <a href="http://code.google.com/closure/compiler/docs/js-for-compiler.html">annotate your JavaScript</a>. Annotating your files allows you to describe them to the compiler. Things like @license will make sure that the comment goes to the top of the file after compression. Look through the <a href="http://code.google.com/closure/compiler/docs/js-for-compiler.html">http://code.google.com/closure/compiler/docs/js-for-compiler.html</a> list to see what each one does. We are going to focus on @define.</p>
<p><span id="more-237"></span></p>
<p>Take the following Code</p>
<pre class="language-javascript">
/**
 * @preserve Copyright 2009 SomeThirdParty.
 * Here is the full license text and copyright
 * notice for this file. Note that the notice can span several
 * lines and is only terminated by the closing star and slash:
 * BORROWED FROM THE ANNOTATED DOCS
 */

/** @define {boolean} */
var DEBUG = true;
var x = 1,
        y = 2;

var myNewObj = function(name, item) {
        var shortName = "Mr " + name,
                longName = "Dr. " + name + " M.D.S";

        this.getShortName = function() {
                if (DEBUG){
                        console.log("I am returning short name: " , shortName)
                }
                return shortName;
        }

        this.getLongName = function() {
                if (DEBUG){
                        console.log("I am returning long name: " , longName)
                }
                return longName;
        }

        return this;
}
// a bunch of your other code her

if (DEBUG) {
        var drWho = new myNewObj("Who", "blank");
        console.log(drWho.getLongName());
}

</pre>
<p>If we run the above code, we get the following output:</p>
<pre class-"language-javascript">
I am returning long name:  Dr. Who M.D.S
Dr. Who M.D.S
</pre>
<p> The above code would allow us to quickly turn on and off the debug statements and see what the JS code was doing. If we use this pattern, we can actually not worry about the value of DEBUG when we are finished with the file. We can actually change the value when we compile the input.</p>
<h2>The compiler</h2>
<p>If you take the above code and compress it using the following command: </p>
<pre class="language-java">
	java -jar compiler.jar --js input.js --define=DEBUG=false --js_output_file output.js --compilation_level SIMPLE_OPTIMIZATIONS --formatting PRETTY_PRINT
</pre>
<p>It will turn the output into:</p>
<pre class="language-javascript">
/*
 Copyright 2009 SomeThirdParty.
 Here is the full license text and copyright
 notice for this file. Note that the notice can span several
 lines and is only terminated by the closing star and slash:
 BORROWED FROM THE ANNOTATED DOCS
*/
var DEBUG = !1, x = 1, y = 2, myNewObj = function(a) {
  var b = "Mr " + a, c = "Dr. " + a + " M.D.S";
  this.getShortName = function() {
    DEBUG &#038;&#038; console.log("I am returning short name: ", b);
    return b
  };
  this.getLongName = function() {
    DEBUG &#038;&#038; console.log("I am returning long name: ", c);
    return c
  };
  return this
};
if(DEBUG) {
  var drWho = new myNewObj("Who", "blank");
  console.log(drWho.getLongName())
}
;
</pre>
<p>The compiled code now outputs the following:</p>
<pre class-"language-javascript">
undefined
</pre>
<p>The return output for the new code is blank</p>
<h2>Advanced Compiling</h2>
<p>We can actually take this one step further, but be warned this is not for the faint of heart. If you want the statements removed completely you will need to rework your code just a bit.</p>
<p>Lets start with a modified version of the starting code:</p>
<pre class="language-javascript">
	/**
	* @preserve Copyright 2009 SomeThirdParty.
	* Here is the full license text and copyright
	* notice for this file. Note that the notice can span several
	* lines and is only terminated by the closing star and slash:
	* BORROWED FROM THE ANNOTATED DOCS
	*/                

	/** @define {boolean} */
	var DEBUG = true;
	var x = 1,              
	y = 2;          

	(function() {
	        /**
	          * A new Obj
	          * @constructor 
	          */            
	        myNewObj = function (name, item) {
	                this.shortName = "Mr " + name,
	                this.longName = "Dr. " + name + " M.D.S";

	                return this;
	        }

	        myNewObj.prototype.getLongName = function() {
	                /** 
	                  * @this {myNewObj}
	                  * @return {string}
	                  */
	                if (DEBUG){
	                        console.log("I am returning long name: " , this.longName)
	                }
	                return this.longName;
	        }

	        myNewObj.prototype.getShortName = function() { 
	                if (DEBUG){
	                        console.log("I am returning short name: " , this.shortName)
	                }
	                return this.shortName;
	        }

	        myNewObj.prototype['getLongName'] = myNewObj.prototype.getLongName;
	        myNewObj.prototype['getShortName'] = myNewObj.prototype.getShortName;

	        if (DEBUG) {
	                var drWho = new myNewObj("Who", "blank");
	                console.log(drWho.getLongName());
	        }
	})();
</pre>
<p>Here we moved the code into a closure function.</p>
<pre class="language-javascript">
	(function() {
	})();
</pre>
<p>Next we split the myNewObj into a constructor and prototypical inheritance. We also added a new annotation: @constructor. This tells the compiler that it is able to be invoked from other areas of the code.</p>
<pre class="language-javascript">
	/**
	  * A new Obj
	  * @constructor 
	  */            
	myNewObj = function (name, item) {
	        this.shortName = "Mr " + name,
	        this.longName = "Dr. " + name + " M.D.S";

	        return this;
	}

	myNewObj.prototype.getLongName = function() {
	        /** 
	          * @this {myNewObj}
	          * @return {string}
	          */
	        if (DEBUG){
	                console.log("I am returning long name: " , this.longName)
	        }
	        return this.longName;
	}

	myNewObj.prototype.getShortName = function() { 
	        /** 
	          * @this {myNewObj}
	          * @return {string}
	          */
	        if (DEBUG){
	                console.log("I am returning short name: " , this.shortName)
	        }
	        return this.shortName;
	}
</pre>
<p>Next, we need to make sure that the functions are available to everyone else. Since the advanced compiler will change all variable names, and delete portions of code that aren&#8217;t reachable, we will make them reachable again. We do this by attaching each of the available functions onto the objects prototype again. For more information on this, check out <a href="http://code.google.com/closure/compiler/docs/api-tutorial3.html#export">Advanced Compilation and Externs</a> tutorial on Closure Compiler.</p>
<pre class="language-javascript">

	myNewObj.prototype['getLongName'] = myNewObj.prototype.getLongName;
	myNewObj.prototype['getShortName'] = myNewObj.prototype.getShortName;	

</pre>
<p>Now that we have the JavaScript setup properly, we can compile to see what the output becomes. We compile the code with the following options</p>
<pre class="language-java">
	java -jar compiler.jar --js input.js --define=DEBUG=false --js_output_file output.js --compilation_level ADVANCED_OPTIMIZATIONS --formatting PRETTY_PRINT --generate_exports
</pre>
<p>It will turn the output into:</p>
<pre class="language-javascript">
/*
 Copyright 2009 SomeThirdParty.
 Here is the full license text and copyright
 notice for this file. Note that the notice can span several
 lines and is only terminated by the closing star and slash:
 BORROWED FROM THE ANNOTATED DOCS
*/
myNewObj = function(a) {
  this.d = "Mr " + a;
  this.c = "Dr. " + a + " M.D.S";
  return this
};
myNewObj.prototype.a = function() {
  return this.c
};
myNewObj.prototype.b = function() {
  return this.d
};
myNewObj.prototype.getLongName = myNewObj.prototype.a;
myNewObj.prototype.getShortName = myNewObj.prototype.b;
</pre>
<h2>Summary</h2>
<p>Don&#8217;t feel overwhelmed trying out the advanced optimizations. Sometimes it just takes some playing around with the code to get it into the best possible outcome. If you aren&#8217;t that familiar with JavaScript, I would highly recommend sticking with the SIMPLE_OPTIMIZATIONS and just having a slightly bigger file to content with.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2012/02/01/removing-debug-statements-from-javascript-via-compiler/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>A Textmate Bundle for CSSLint</title>
		<link>http://scriptble.com/2011/06/17/a-textmate-bundle-for-csslint/</link>
		<comments>http://scriptble.com/2011/06/17/a-textmate-bundle-for-csslint/#comments</comments>
		<pubDate>Fri, 17 Jun 2011 22:07:55 +0000</pubDate>
		<dc:creator>jcfant</dc:creator>
				<category><![CDATA[CSSLint]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=228</guid>
		<description><![CDATA[CSSLint A quick heads up, if you haven&#8217;t heard about the new CSSLint project from Nicole ## and Nicholas Zakas, you have been missing out. The project aims to take CSS to the next level and help you understand why your css isn&#8217;t performing very well. What, you didn&#8217;t know your CSS isn&#8217;t performing? Thats [...]]]></description>
				<content:encoded><![CDATA[<h1>CSSLint</h1>
<p>A quick heads up, if you haven&#8217;t heard about the new <a href="http://csslint.net">CSSLint</a> project from Nicole ## and Nicholas Zakas, you have been missing out. The project aims to take CSS to the next level and help you understand why your css isn&#8217;t performing very well. What, you didn&#8217;t know your CSS isn&#8217;t performing? Thats because most of us haven&#8217;t had a good Code Review on most of our CSS.</p>
<h2>CSSLint for TextMate</h2>
<p>First and foremost, I would like to say, <b>I forked the original <a href="http://fgnass.posterous.com/jslint-in-textmate">jsHint TextMate Bundle</a></b>. If you don&#8217;t already have this, you need it. It will change the way you put together your JavaScript, just as I suspect CSSLint will do for your CSS.</p>
<p>I talked with Nicholas at the Velocity conference and decided I would put together a quick <a href="https://github.com/jcfant/csslint.tmbundle">CSSLint TextMate Bundle</a> that could make use of the Node Module for CSSLint. After a couple of hours playing with the way TextMate Does its bundles, I was able to get a working product. A Couple of quick emails back and forth and we have a Beta version of the CSSLint TextMate Bundle.</p>
<p><span id="more-228"></span></p>
<h3>Installation</h3>
<p>Installation is simple. Just download this file <a href="http://github.com/jcfant/csslint.tmbundle/zipball/master">CSSLint TextMate Bundle</a>. Unzip the contents, and then rename the file to csslint.tmbundle.</p>
<p>Once you have renamed, just double click on the icon, and it should automatically add it to TextMate.</p>
<h3>Prerequisites</h3>
<p>You need <a href="http://nodejs.org/">Node.js</a> and TextMate, that&#8217;s all.</p>
<p>If you don&#8217;t have <a href="http://nodejs.org/">Node.js</a> installed on your system you can also use <a href="https://github.com/bpierre/jshint.tmbundle">Pierre Bertet&#8217;s</a> fork which uses <a href="http://trac.webkit.org/wiki/JSC">WebKit&#8217;s JavaScriptCore</a> instead.</p>
<p>This bundle uses #!/usr/local/bin/node to launch the node process. If you get a node &#8211; not found error,the PATH variable is probably not setup in TextMate.</p>
<h3>Features</h3>
<p>
	A couple of quick highlights.</p>
<ul>
<li>Runs automatically upon save (⌘S)</li>
<li>Can be bypassed by pressing ⇧⌘S</li>
<li>Output is only shown when errors are found</li>
<li>Based on Node.js</li>
</ul>
<h3>ScreenShot</h3>
<p>
<img src="https://github.com/jcfant/images/raw/master/CSSLintTMBundle.jpg" height="384" width="579" />
</p>
<h3>Contributions</h3>
<p>
	Feel free to contact me about any features you would like to see in the bundle. Or submit a pull request and I will take a look.
</p>
<p>Cheers!</p>
<p>JC Fant</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/06/17/a-textmate-bundle-for-csslint/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Parallel Downloading HTML Assets</title>
		<link>http://scriptble.com/2011/05/16/parallel-downloading-html-assets/</link>
		<comments>http://scriptble.com/2011/05/16/parallel-downloading-html-assets/#comments</comments>
		<pubDate>Mon, 16 May 2011 21:10:50 +0000</pubDate>
		<dc:creator>jcfant</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[inline script]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=210</guid>
		<description><![CDATA[Question: Image &#8211; inline Script &#8211; image, are the images parallel? Souders just posted the following tweet. Someone out in #webperf land should test how inline scripts block downloads &#8211; eg, image &#8211; inline script &#8211; image &#8211; are the images parallel? So here is my response to the question&#8230; Answer: No The Test Page [...]]]></description>
				<content:encoded><![CDATA[<h1>Question: Image &#8211; inline Script &#8211; image, are the images parallel?</h1>
<p>Souders just posted the following tweet.</p>
<blockquote><p>Someone out in #webperf land should test how inline scripts block downloads &#8211; eg, image &#8211; inline script &#8211; image &#8211; are the images parallel?</p></blockquote>
<p> So here is my response to the question&#8230; </p>
<p><span id="more-210"></span></p>
<h1>Answer: No</h1>
<h2>The Test Page</h2>
<p>
	The page itself is pretty simple, two images served from <a href="http://placehold.it/">placehold.it</a> and in between them, jQuery 1.5.2 in an inline script block.<br />
	Take a look at the <a href="/tests/scriptTest.html">sample test here</a>.
</p>
<h2>The Tests</h2>
<p>
	Using <a href="http://webpagetest.org">webpagetest.org</a>, I ran the scriptTest.html file through IE6|7|8|9 and Chrome 11. In each of the browsers the waterfall graph<br />
	comes out the same. The inline script blocks any more downloads until the script has finished parsing and been run.
</p>
<h2>Waterfall Graphs</h2>
<p>Here are the waterfall graphs for each of the browsers on webpagetest.org</p>
<h3>IE6</h3>
<p><img src="http://www.webpagetest.org/results/11/05/16/S0/M7QN/1_waterfall.png" width="585" height="128"/></p>
<p><a href="http://www.webpagetest.org/result/110516_S0_M7QN/1/details/">Test Results</a></p>
<h3>IE7</h3>
<p><img src="http://www.webpagetest.org/results/11/05/16/3K/M7QP/1_waterfall.png" width="585" height="128" /></p>
<p><a href="http://www.webpagetest.org/result/110516_3K_M7QP/1/details/">Test Results</a></p>
<h3>IE8</h3>
<p><img src="http://www.webpagetest.org/results/11/05/16/GE/M7QQ/1_waterfall.png" width="585" height="128" /></p>
<p><a href="http://www.webpagetest.org/result/110516_GE_M7QQ/1/details/">Test Results</a></p>
<h3>IE9</h3>
<p><img src="http://www.webpagetest.org/results/11/05/16/CA/M7QS/1_waterfall.png" width="585" height="128" /></p>
<p><a href="http://www.webpagetest.org/result/110516_CA_M7QS/1/details/">Test Results</a></p>
<h3>Chrome 11</h3>
<p><img src="http://www.webpagetest.org/results/11/05/16/DC/M7QT/1_waterfall.png" width="585" height="128" /></p>
<p><a href="http://www.webpagetest.org/result/110516_DC_M7QT/1/details/">Test Results</a></p>
<h2>But Wait!</h2>
<p>This isn&#8217;t just about images and inline style blocks. What happens when we use a style sheet? Will it give the same behavior?</p>
<h2>Next Test</h2>
<p>Here is a <a href="http://scriptble.com/tests/scriptTestStyles.html">new test</a>, it has an external style sheet (style.css), the inline JavaScript block, another external style sheet (screen.css) and an image from placehold.it.<br />
<h2>Results</h2>
<p>In each case the inline JavaScript is blocking the page from getting any more resources. As soon as the JavaScript has been processed it can then move on to getting the background image, screen.css and the placeholder.it image.<br />
<h3>IE6</h3>
<p><img src="http://www.webpagetest.org/results/11/05/16/ST/M7T9/1_waterfall.png" width="585" height="128" /></p>
<p><a href="http://www.webpagetest.org/result/110516_ST_M7T9/1/details/">Test Results</a></p>
<h3>IE7</h3>
<p><img src="http://www.webpagetest.org/results/11/05/16/HX/M7TC/1_waterfall.png" width="585" height="128" /></p>
<p><a href="http://www.webpagetest.org/result/110516_HX_M7TC/1/details/">Test Results</a></p>
<h3>IE8</h3>
<p><img src="http://www.webpagetest.org/results/11/05/16/D0/M7TE/1_waterfall.png" width="585" height="128" /></p>
<p><a href="http://www.webpagetest.org/result/110516_D0_M7TE/1/details/">Test Results</a></p>
<h3>IE9</h3>
<p><img src="http://www.webpagetest.org/results/11/05/16/04/M7TH/1_waterfall.png" width="585" height="128" /></p>
<p><a href="http://www.webpagetest.org/result/110516_04_M7TH/1/details/">Test Results</a></p>
<h3>Chrome 11</h3>
<p><img src="http://www.webpagetest.org/results/11/05/16/6N/M7TN/1_waterfall.png" width="585" height="128" /></p>
<p><a href="http://www.webpagetest.org/result/110516_6N_M7TN/1/details/">Test Results</a></p>
<h2>Conclusion</h2>
<p>Be careful with your inline blocks. They CAN AND WILL hold up the rest of your page when they are encountered.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/05/16/parallel-downloading-html-assets/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Getting A Class From a DOM Element</title>
		<link>http://scriptble.com/2011/05/13/getting-a-class-from-a-dom-element/</link>
		<comments>http://scriptble.com/2011/05/13/getting-a-class-from-a-dom-element/#comments</comments>
		<pubDate>Fri, 13 May 2011 19:34:32 +0000</pubDate>
		<dc:creator>jcfant</dc:creator>
				<category><![CDATA[Do This, Not That]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[DOM Manipulation]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=200</guid>
		<description><![CDATA[Lately, if I am searching for a way to do something in Javascript the only results I am getting ways of doing the procedure using jQuery. While, its true jQuery is pretty much the de facto standard for writing JavaScript anymore, understanding the underlying technology is a must. As well as alot of times, I [...]]]></description>
				<content:encoded><![CDATA[<p>Lately, if I am searching for a way to do something in Javascript the only results I am getting ways of doing the procedure using jQuery. While, its true jQuery is pretty much the de facto standard for writing JavaScript anymore, understanding the underlying technology is a must. As well as alot of times, I don&#8217;t need to load jQuery on the page just to get a DOM Element or its class.</p>
<p>So I recently went looking on how to <a href="http://tinyurl.com/3w5m6t5">get class from element</a> in JavaScript. Turns out most of the results were for getting elements by class name, rather than actually getting the class of the element I already had.</p>
<p>Here is how you get a class name from an Element using JavaScript.</p>
<p><span id="more-200"></span></p>
<pre class="language-javascript">
	document.getElementById("tag_cloud-2").className
</pre>
<p><br/></p>
<pre>
	Output:
		"sidebaritem widget_tag_cloud"
</pre>
<p><br/></p>
<p>Now, that wasn&#8217;t so hard.  Lets take a look at a performance test: <a href="http://jsperf.com/jquery-versus-classname">jQuery versus getting a className</a>.</p>
<p>Here is the setup for the test</p>
<pre>
&lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"&gt;&lt;/script&gt;

&lt;div class="wrapper"&gt;
	&lt;div class="innerWrapper"&gt;
		&lt;div id="getMe" class="button"&gt;
			&lt;a href="javascript:void(0)" id="button" class="buttonRef"&gt;
				&lt;span class="buttonText"&gt;Text&lt;/span&gt;
			&lt;/a&gt;
		&lt;/div&gt;
	&lt;/div&gt;
&lt;/div&gt;

&lt;script&gt;
	var jElem = $("#getMe");
	var dElem = document.getElementById("getMe");
&lt;/script&gt;
</pre>
<p><br/></p>
<p>Here are the tests:</p>
<pre>
1. jQuery - get Element + get Class   $("#getMe").attr('class');
2. GET DOM ELEM + get Class           document.getElementById("getMe").className;
3. jQuery get Class                   jElem.attr('class');
4. DOM get class                      dElem.className;
</pre>
<h2>Chrome 11 Results</h2>
<p>
In Chrome using a cached element, getting the classname is 48x faster than using jQuery.<br/><br />
In Chrome getting the element and then getting the classname is 25x faster than using jQuery.<br/>
</p>
<h2>FF 4.0 Results</h2>
<p>
In FF using a cached element, getting the classname is 65x faster than using jQuery.<br/><br />
In FF getting the element and then getting the classname is 83x faster than using jQuery.<br/>
</p>
<h2>Safari 5.0 Results</h2>
<p>
In Safari using a cached element, getting the classname is 30x faster than using jQuery.<br/><br />
In Safari getting the element and then getting the classname is 35x faster than using jQuery.<br/>
</p>
<h3>Summary</h3>
<p>
	Whenever possible, using the browsers built in methods will always be faster, and just because you have a library available doesn&#8217;t mean you should be using it for every DOM query. The speed advantage alone should dictate which methods of the library you are using and when.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/05/13/getting-a-class-from-a-dom-element/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Lazy Loading Functions</title>
		<link>http://scriptble.com/2011/05/12/lazy-loading-functions/</link>
		<comments>http://scriptble.com/2011/05/12/lazy-loading-functions/#comments</comments>
		<pubDate>Fri, 13 May 2011 04:05:52 +0000</pubDate>
		<dc:creator>jcfant</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Functions]]></category>
		<category><![CDATA[Objects]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=193</guid>
		<description><![CDATA[The best part about this Javascript pattern is the ability to calculate once and then use the new function definition from that point forward. During the course of building web apps, we usually end up with functions to do certain tasks. However, since those tasks sometimes need to be done differently in each of the [...]]]></description>
				<content:encoded><![CDATA[<p>The best part about this Javascript pattern is the ability to calculate once and then use the new function definition from that point forward.</p>
<p>During the course of building web apps, we usually end up with functions to do certain tasks. However, since those tasks sometimes need to be done differently in each of the browsers, we end up with large if else statements to get the job done.</p>
<p>This is where Self Defining Functions come in handy.</p>
<p><span id="more-193"></span></p>
<p>Here is a simple Person Object that has a getPayInformation object. Lets assume for the sake of the argument that this function is called 100&#8242;s of times. In this case, each time the getPayInformation function is called, it first has to figure out the role, then do the calculations for the pay.</p>
<pre class="language-javascript">
function Person(name, role) {
    if (!(this instanceof Person)){
        return new Person(name, role);
    }

    this.name = name || "John";
	this.role = role || "Guest";
};

Person.prototype.getPayInformation = function() {
	if (this.role === "Admin"){
		// fetch some data for the admin role. 
		// do some awesome calculations to munge the data 
		// ...
		return {
			"role"  : "Admin",
			"rate"  : 10.00,
			"hours" : 40
		};
	}else if (this.role === "CopyCat"){
		// fetch some data for the admin role. 
		// Calculating the Info for a copy cat is harder. Has some different calculations based on 
		// how many words they wrote
		// ...
		return {
			"role"  : "CopyCat",
			"rate"  : 37.00,
			"hours" : 23
		};
	}else if (this.role === "Crane Operator"){
		// fetch some data for the admin role. 
		// Calculating the info for a crane operator is based on hourly, anything over 40 is time and a half.
		// ...
		return {
			"role"  : "Crane Operator",
			"rate"  : 90.00,
			"hours" : 42
		};
	}else{ 
		// fetch some data for the admin role. 
		// we don't need to do anything for the guest, its always 0.
		// ...
		return {
			"role"  : "Guest",
			"rate"  : 0.00,
			"hours" : 0
		};
	}
}
</pre>
<p><br/></p>
<p>What would happen if we knew that after the first time through this person was an admin. We would no longer need to do that check over and over again.</p>
<pre class="language-javascript">
function Person(name, role) {
    if (!(this instanceof Person)){
        return new Person(name, role);
    }

    this.name = name || "John";
	this.role = role || "Guest";
};

Person.prototype.getPayInformation = function() {
	if (this.role === "Admin"){
		this.getPayInformation = function() {
			console.log("Lazy Function Definition");
			// fetch some data for the admin role. 
			// do some awesome calculations to munge the data 
			// ...
			return {
				"role"  : "Admin",
				"rate"  : 10.00,
				"hours" : 40
			};
		}
		return this.getPayInformation();
	}else if (this.role === "CopyCat"){
		this.getPayInformation = function() {
			console.log("Lazy Function Definition");
			// fetch some data for the admin role. 
			// Calculating the Info for a copy cat is harder. Has some different calculations based on 
			// how many words they wrote
			// ...
			return {
				"role"  : "CopyCat",
				"rate"  : 37.00,
				"hours" : 23
			};
		}
		return this.getPayInformation();
	}else if (this.role === "Crane Operator"){
		this.getPayInformation = function() {
			console.log("Lazy Function Definition");
			// fetch some data for the admin role. 
			// Calculating the info for a crane operator is based on hourly, anything over 40 is time and a half.
			// ...
			return {
				"role"  : "Crane Operator",
				"rate"  : 90.00,
				"hours" : 42
				};	
		}
		return this.getPayInformation();
	}else{ 
		this.getPayInformation = function() {
			console.log("Lazy Function Definition");
			// fetch some data for the admin role. 
			// we don't need to do anything for the guest, its always 0.
			// ...
			return {
				"role"  : "Guest",
				"rate"  : 0.00,
				"hours" : 0
			};	
		}
		return this.getPayInformation();
	}
}
</pre>
<p><br/></p>
<p>Now, we only have to do the check once and then each subsequent calls can skip the check and just get to work.</p>
<p>So what does the output look like?</p>
<pre class="language-javascript">
	var tammy = new Person("Tammy", "Admin");
	console.log(tammy.getPayInformation());
		"Lazy Function Definition"
		> Object
			{
				"role"  : "Admin",
				"rate"  : 10.00,
				"hours" : 40
			}
			
	var john = new Person("John", "Guest");
	console.log(john.getPayInformation());
		"Lazy Function Definition"
		> Object
			{
				"role"  : "Guest",
				"rate"  : 0.00,
				"hours" : 0
			}
	
	var lola = new Person("Lola", "CopyCat");
	console.log(lola.getPayInformation());
		"Lazy Function Definition"
		> Object
			{
				"role"  : "CopyCat",
				"rate"  : 37.00,
				"hours" : 23
			}
			
	var chad = new Person("Chad", "Crane Operator");
	console.log(chad.getPayInformation());
		"Lazy Function Definition"
		> Object
			{
				"role"  : "Crane Operator",
				"rate"  : 90.00,
				"hours" : 42
			}
</pre>
<p><br/></p>
<p>Looks to be a pretty neat way to do Browser Feature detection instead of nested if statements. Moving to a Module pattern helps to support the Self Defining Function Pattern.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/05/12/lazy-loading-functions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery ready, delegate, live!</title>
		<link>http://scriptble.com/2011/03/09/jquery-ready-delegate-live/</link>
		<comments>http://scriptble.com/2011/03/09/jquery-ready-delegate-live/#comments</comments>
		<pubDate>Wed, 09 Mar 2011 18:18:51 +0000</pubDate>
		<dc:creator>jcfant</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[.delegate()]]></category>
		<category><![CDATA[.live()]]></category>
		<category><![CDATA[.ready()]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=177</guid>
		<description><![CDATA[Recently I was browsing through the jQuery subr reddit and noticed this question pop up. Since I am sure this is a pretty common question on &#8220;Why won&#8217;t my jQuery command work properly&#8221;, I figured I would give a shot at answering it. Hey guys, I&#8217;m sure this has been answered before but I can&#8217;t [...]]]></description>
				<content:encoded><![CDATA[<p>
	Recently I was browsing through the jQuery subr reddit and noticed this question pop up. Since I am sure this is a pretty common question on &#8220;Why won&#8217;t my jQuery command work properly&#8221;, I figured I would give a shot at answering it.
</p>
<blockquote><p>
Hey guys, I&#8217;m sure this has been answered before but I can&#8217;t seem to find anything by searching Google or /r/jquery.</p>
<p>I am a beginner with this so forgive me, but I can&#8217;t find an explanation to this anywhere and I&#8217;m curious. When I try to stop the default submit function of a form in the &lt;head&gt; tag of a .html file it won&#8217;t work, but when I copy and paste the same code into the &lt;body&gt; it works fine. Regardless of where I place it, it is always below the link to the jquery library. This is really confusing and I was hoping you guys could explain this for me. Thanks!</p>
<p>via <a href="http://www.reddit.com/r/jquery/comments/fwtwh/jquery_script_in_body_or_head/">jQuery &lt;script&gt; in &lt;body&gt; or *lt;head&gt;</a>.
</p></blockquote>
<p><span id="more-177"></span></p>
<h2>Problem</h2>
<p>
	Here was a copy of the code that worked:
</p>
<p><code class="language-javascript"><br />
&lt;html&gt;<br />
	&lt;head&gt;<br />
		&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"&gt;&lt;/script&gt;</p>
<p>	&lt;/head&gt;<br />
	&lt;body&gt;</p>
<p>	&lt;script&gt;<br />
    	$("form").submit(function(){<br />
        	return false;<br />
    		});<br />
	&lt;/script&gt;<br />
	&lt;form id="uriForm" action=""&gt;<br />
		&lt;input type="textbox" name="uriInput" id="uriInput" /&gt;<br />
		&lt;input type="submit" value="submit" id="submit" /&gt;<br />
	&lt;/form&gt;<br />
	&lt;/body&gt;<br />
&lt;/html&gt;<br />
</code><br />
<br/></p>
<p>
	However, if he moved the &lt;script&gt; tag into the head, the form submit stopped working.
</p>
<p><code class="language-javascript"><br />
	&lt;head&gt;<br />
		&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"&gt;&lt;/script&gt;</p>
<p>		&lt;script&gt;<br />
	    	$("form").submit(function(){<br />
	        	return false;<br />
	    		});<br />
		&lt;/script&gt;<br />
	&lt;/head&gt;<br />
</code><br />
<br/></p>
<h2>Why?</h2>
<p>
	Why on earth would the first one work, and the second one not? Well, it comes down to when the dom is ready. In the second example, jQuery is looking for a form tag that hasn&#8217;t been parsed by the browser yet. So it returns an empty jQuery object, to which the submit event is attached.
</p>
<h2>The Fix</h2>
<p>
	We have a couple of ways of fixing this issue.
</p>
<h3>.ready()</h3>
<p>The .ready() event attached to the BODY tag, will allow us to attach the submit event as soon as the DOM is ready</p>
<p><code class="language-javascript"><br />
	$(document).ready(function() {<br />
		$("form").submit(function() {<br />
			return false;<br />
		});<br />
	})<br />
</code><br />
<br/></p>
<h3>.delegate()</h3>
<p>
	The .delegate() method can be placed anywhere in your page. Since the delegate function will attach the event to any current &#8220;form&#8221; elements, or any future &#8220;form&#8221; elements that may appear in the DOM. The gotcha&#8230; If you only have one form element on the page, this will work fine. However, IF for some reason, you create another form element, this same event will be attached to that form as well.
</p>
<p><code class="language-javascript"><br />
	$(document).delegate("form", function() {<br />
		$("form").submit(function() {<br />
			return false;<br />
		});<br />
	})<br />
</code><br />
<br/></p>
<h3>.live()</h3>
<p>
	The .live() method is a variation/alternative of the .delegate() method. However, at least one element must exist before you can use it. Which means, you still need to wrap it in a .ready() or put it in the footer.
</p>
<blockquote><p>
	This method is a variation on the basic .bind() method for attaching event handlers to elements. When .bind()  is called, the elements that the jQuery object refers to get the handler attached; elements that get introduced later do not, so they would require another .bind() call.
</p></blockquote>
<p><code class="language-javascript"><br />
	$(document).ready(function() {<br />
		$("form").live("submit", function() {<br />
			return false;<br />
		});<br />
	})<br />
</code><br />
<br/></p>
<p>
	In all, either .ready() or .delegate() will work, just make sure you use them properly. You don&#8217;t want to add another form or other element and have it get an event you hadn&#8217;t planned on.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/03/09/jquery-ready-delegate-live/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Patterns for enforcing &#8220;new&#8221;</title>
		<link>http://scriptble.com/2011/03/05/patterns-for-enforcing-new/</link>
		<comments>http://scriptble.com/2011/03/05/patterns-for-enforcing-new/#comments</comments>
		<pubDate>Sun, 06 Mar 2011 04:49:59 +0000</pubDate>
		<dc:creator>jcfant</dc:creator>
				<category><![CDATA[Do This, Not That]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[patterns]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=184</guid>
		<description><![CDATA[Recently I was looking around for a book on JavaScript Patterns. I decided to give the JavaScript Patterns by Stoyan Stefanov a try. If you have been looking for a book on Javascript Patterns, I highly recommend this book. In the 3rd chapter, Literals and Constructors, I noticed this section on &#8220;Patterns for enforcing new&#8221; [...]]]></description>
				<content:encoded><![CDATA[<p>
	Recently I was looking around for a book on JavaScript Patterns. I decided to give the <a href="http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752/ref=sr_1_1?ie=UTF8&#038;qid=1299384435&#038;sr=8-1">JavaScript Patterns</a> by Stoyan Stefanov a try. If you have been looking for a book on Javascript Patterns, I highly recommend this book.
</p>
<p>
	In the 3rd chapter, Literals and Constructors, I noticed this section on &#8220;Patterns for enforcing new&#8221; with the following entry:
</p>
<blockquote><p>
	When your constructor has something like <i>this.member</i> and you invoke the constructor without <i>new</i>, you&#8217;re actually creating a new property of the global object called <i>member</i> and accessible through <b>window.<i>member</i></b> or simply <i>member</i>. This behavior is highly undesirable, because you know you should always strive for keeping the global namespace clean.
</p></blockquote>
<p><span id="more-184"></span></p>
<p>
	Take a look at the following code:
</p>
<p><code class="language-javascript"><br />
	function Person(name) {<br />
		this.personName = name || "John";<br />
	}</p>
<p>	var tammy = new Person("tammy");<br />
	console.log(typeof tammy); // Object<br />
	console.log(tammy instanceof Person); // true<br />
	console.log(tammy.personName); // tammy<br />
	console.log(window.personName); // undefined</p>
<p>	var jason = Person("jason");<br />
	console.log(typeof jason); // undefined<br />
	console.log(jason instanceof Person); // false<br />
	console.log(window.personName); // jason<br />
</code><br />
<br/></p>
<p>
	Eek! Thats not what I expected at all. So how can we force this to always create a new Object each time, regardless of whether or not the Object (&#8220;function&#8221;) has been called with new?
</p>
<h2>Solutions</h2>
<p>
	There are a couple of solutions. We can either, change the scope of the internal variable to something other than &#8220;this&#8221; OR we can always force a &#8220;new&#8221; on the object.
</p>
<h3>Use &#8220;that&#8221;</h3>
<p>
	If we change the function to create a new object called &#8220;that&#8221; and then assign personName to the new object, we can make sure that the global namespace isn&#8217;t polluted.
</p>
<p><code class="language-javascript"><br />
	function Person(name) {<br />
		var that = {};<br />
		that.personName = name || "John";</p>
<p>		return that;<br />
	}</p>
<p>	var tammy = new Person("tammy");<br />
	console.log(typeof tammy); // Object<br />
	console.log(tammy instanceof Person); // false<br />
	console.log(tammy.personName); // tammy<br />
	console.log(window.personName); // undefined</p>
<p>	var jason = Person("jason");<br />
	console.log(typeof jason); // Object<br />
	console.log(jason instanceof Person); // false<br />
	console.log(jason.personName); // jason<br />
	console.log(window.personName); // undefined<br />
</code><br />
<br/></p>
<p>
	Well, that is much better. However, if we check whether or not &#8220;jason&#8221; or &#8220;tammy&#8221; are actually people we see that both fail. So while this gets us to the point of not polluting the global namespace we aren&#8217;t creating actual &#8220;people&#8221;.
</p>
<h3>Force &#8220;new&#8221;</h3>
<p>
	We can actually check to see if &#8220;this&#8221; is an instance of Person, if not, returning a &#8220;new Person&#8221;.
</p>
<p><code class="language-javascript"><br />
	function Person(name) {<br />
		if (!(this instanceof Person)){<br />
			return new Person(name);<br />
		}</p>
<p>		this.personName = name || "John";</p>
<p>	}</p>
<p>	var tammy = new Person("tammy");<br />
	console.log(typeof tammy); // Object<br />
	console.log(tammy instanceof Person); // true<br />
	console.log(tammy.personName); // tammy<br />
	console.log(window.personName); // undefined</p>
<p>	var jason = Person("jason");<br />
	console.log(typeof jason); // Object<br />
	console.log(jason instanceof Person); // true<br />
	console.log(jason.personName); // jason<br />
	console.log(window.personName); // undefined<br />
</code><br />
<br/></p>
<p>
	Much better, now we actually have true instances of &#8220;Person&#8221;.
</p>
<p>
	The good news in all of this is that in ECMAScript5 strict mode, this no longer applies. As the &#8220;this&#8221; reference will no longer point to the global namespace.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/03/05/patterns-for-enforcing-new/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Closure Versus Prototypal Object Creation</title>
		<link>http://scriptble.com/2011/02/17/closure-versus-prototypal-object-creation/</link>
		<comments>http://scriptble.com/2011/02/17/closure-versus-prototypal-object-creation/#comments</comments>
		<pubDate>Fri, 18 Feb 2011 05:14:16 +0000</pubDate>
		<dc:creator>jcfant</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=162</guid>
		<description><![CDATA[I was just looking through a new blog post from Brendan Eich over on AMinuteWithBrendan where he went into some detail on Closures versus Prototypal Patterns. After listening to his pod cast, (you can find the transcript here), I decided to put the two patterns to test. So I fired up a new test on [...]]]></description>
				<content:encoded><![CDATA[<p>
	I was just looking through a new blog post from Brendan Eich over on<br />
	<a href="http://www.aminutewithbrendan.com/">AMinuteWithBrendan</a> where he went into some detail on <a href="http://www.aminutewithbrendan.com/pages/20110216">Closures versus<br />
	Prototypal Patterns</a>.
</p>
<p>After listening to his pod cast, (you can find the transcript <a href="http://piratepad.net/amwb-20110216">here</a>), I decided to put<br />
the two patterns to test. So I fired up a new test on <a href="http://jsperf.com/object-creation-patterns">JSPerf.com</a></p>
<p><span id="more-162"></span><br />
<br/><br/><br/><br/></p>
<h5>Setting up the Closure Pattern</h5>
<p><code class="language-javascript"><br />
 function ClosurePattern() {<br />
  this.someMethod = function someMethod() {<br />
   console.log('foo');<br />
  }<br />
 }<br />
 </code><br />
 <br/></p>
<h5>Setting up the Prototypal Pattern</h5>
<p> <code class="language-javascript"><br />
 function PrototypalPattern() {}<br />
 PrototypalPattern.prototype = {<br />
  someMethod: function() {<br />
   console.log('foo');<br />
  }<br />
 }<br />
 </code></p>
<h5>Setting up the Prototypal Hoisting Pattern</h5>
<p> <code class="language-javascript"><br />
 function sm() {<br />
  console.log("foo")<br />
 }</p>
<p> function PrototypalWithHoisting() {}<br />
 PrototypalWithHoisting.prototype = {<br />
  someMethod: sm<br />
 }<br />
 </code><br />
<br/></p>
<h3>Results</h3>
<h5>Closure Pattern</h5>
<p><img src="/images/closurePatterns/closure.png" alt="Closure Pattern"/><br />
<br/><br />
<br/></p>
<p>The closure pattern is quick in Chrome, but not nearly as fast in all the other browsers.</p>
<h5>Prototypal Versus Hoisting</h5>
<p><img src="/images/closurePatterns/prototypalVhoisting.png" alt="Prototypal Versus Hoisting"/><br />
<br/><br />
<br/></p>
<p>Prototypal and hoisting run neck and neck in all browsers, with Prototypal winning out in Chrome.</p>
<h5>Closure Versus Prototypal</h5>
<p><img src="/images/closurePatterns/closureVersusPrototype.png" alt="Closure Versus Prototypal"/><br />
<br/><br />
<br/></p>
<p>Here we are can start to se the overall winner in object creation.</p>
<h5>Closure, Prototypal, Hoisting</h5>
<p><img src="/images/closurePatterns/closureAndProto.png" alt="Closure, Prototypal, Hoisting"/><br />
<br/><br />
<br/></p>
<p>I threw this one up here so you can see all 3 types next to each other. </p>
<h3>Conclusion</h3>
<p>
	After look at this set of test, I really think it all depends on your use case. While the Closure Pattern lends itself to<br />
	readability and the ability to have both public and private variables as well as public and private methods, object creation is<br />
	much slower. Also, as Brendan points out, you aren&#8217;t getting the same functionality as creating an object via the Prototypal Pattern.
</p>
<blockquote><p>
	The closure pattern, the one where you have the method as a function expression inside the constructor, can actually be more<br />
	expensive. If you think about it, each time you call that constructor (let&#8217;s say you call it a million times), you have to<br />
	evaluate the method function expression. You have to evaluate the assignment &#8220;this.someMethod = function() { /*etc*/ }&#8221;. In<br />
	JavaScript, every time you evaluate a function expression, you get a new object. You can tell it&#8217;s a new object because<br />
	of &#8220;===&#8221;; you can also mutate it: it&#8217;s mutable. So you can set a certain property on it that would not show up on any other<br />
	instances &#8212; &#8220;someMethod&#8221;. You&#8217;d say &#8220;new ClosurePattern()&#8221; and assign that to x, and also set y to &#8220;new ClosurePattern()&#8221;.<br />
	Now you&#8217;ve got two instances. x.someMethod !== y.someMethod, and &#8220;x.someMethod.foo = 42&#8243; would not cause 42 to appear on<br />
	y.someMethod: they&#8217;d be different objects. That hurts! If you do a million constructions, you&#8217;ve got not just a million<br />
	instances of the ClosurePattern object, you&#8217;ve got a million &#8220;someMethod&#8221;s inside it.
</p></blockquote>
<p><br/></p>
<p>
	Unless I was creating an application that requires creating millions of JavaScript objects, I would still recommend the Closure<br />
	Pattern for code re-use.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/02/17/closure-versus-prototypal-object-creation/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced
Object Caching 498/498 objects using disk: basic

Served from: scriptble.com @ 2013-05-25 12:34:18 -->