<?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>AddyOsmani.com &#124; Where Web Businesses Grow &#187; testing</title>
	<atom:link href="http://addyosmani.com/blog/tag/testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://addyosmani.com/blog</link>
	<description>This is the home of Addy Osmani (Web Developer, Designer &#38; Author). Here you can find some great tips and tutorials on everything to do with web development and even a few useful code samples!</description>
	<lastBuildDate>Sun, 25 Jul 2010 14:41:34 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>11 Ways to Increase Your jQuery Performance</title>
		<link>http://addyosmani.com/blog/11-ways-to-increase-your-jquery-performance/</link>
		<comments>http://addyosmani.com/blog/11-ways-to-increase-your-jquery-performance/#comments</comments>
		<pubDate>Wed, 11 Nov 2009 23:06:34 +0000</pubDate>
		<dc:creator>Addy</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[faster]]></category>
		<category><![CDATA[improve]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[optimal]]></category>
		<category><![CDATA[optimization]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://addyosmani.com/blog/11-ways-to-increase-your-jquery-performance/</guid>
		<description><![CDATA[&#160; This post will give you 11 easy steps that are going to instantly improve your jQuery application’s performance. There isn’t anything that difficult in here and almost anyone can apply these methods to their project. If you’ve got a few extra tips you would like to share, please feel free to include them in [...]]]></description>
			<content:encoded><![CDATA[<p>&nbsp;</p>
<p>This post will give you 11 easy steps that are going to instantly improve your jQuery application’s performance. There isn’t anything that difficult in here and almost anyone can apply these methods to their project. If you’ve got a few extra tips you would like to share, please feel free to include them in the comments section. We’d love to hear from you!.</p>
<p>&nbsp;</p>
<p><a class="thickbox" href="http://addyosmani.com/blog/wp-content/uploads/2009/11/cheatsheet.png"><img title="cheatsheet" style="border-top-width: 0px; display: block; border-left-width: 0px; float: none; border-bottom-width: 0px; margin-left: auto; margin-right: auto; border-right-width: 0px" height="163" alt="cheatsheet" src="http://addyosmani.com/blog/wp-content/uploads/2009/11/cheatsheet_thumb.png" width="516" border="0"></a> </p>
<p><span id="more-229"></span>
<p>&nbsp;
<p>Optimization is something that can help the users of your application achieve actions inside of it much quicker than they may currently be able to. Looking for a way to make that animated drag look smoother? Perhaps you’re accessing it using the least-optimal path. That navigation menu working slow? Perhaps you just need to get rid of some of the waste in your calls. If you feel like your script or jQuery app could use a little performance optimization, read on because this article is sure to help.
<p>&nbsp;
<p>Before we get started I would like for everyone to remember that you should only strive for optimization when there is a measured need for optimization. Changing neat code to something you or your developers may not be used to is something I would not advise unless you are all well experienced with jQuery and JavaScript syntax. jQuery is still blazingly fast without any performance improvements added (in a lot of cases). Most often, one cannot tell without resorting to metrics or viewing source if it’s the server that delivered these bits in the page, or client-side JavaScript.
<p>&nbsp;
<p>Some of the tips that in this article will seem straight-forward to some, but I think that giving ourselves a “refresher” is always helpful. I would also like to remind everyone that the man behind jQuery itself (John Resig) strongly recommends that your jQuery applications be heavily performance tested. There are some amazing articles on how to performance test your apps including <a href="http://ejohn.org/blog/deep-profiling-jquery-apps/">this one</a> from Resig on performance testing (which comes with a free plugin), this one on <a href="http://blog.dynatrace.com/2009/04/20/how-to-test-jquery-enabled-apps-using-json-with-visual-studio/">Ajax/JSON testing within Visual Studio</a> and Paul Irish’s interesting presentation on Anti-patterns in performance and compression <a href="http://www.slideshare.net/paul.irish/perfcompression">here</a>. If you are going to try improving the performance of your application, guage how long it takes for core functions to be executed, discover what is causing any slow-down (is it the server? is the browser? is it the rendering engine, or is it my code?) and then set out a plan for how you are going to improve your application.
<p>&nbsp;
<p>With that in mind, let us begin!.
<p>&nbsp;<br />
<h4>jQuery Performance Tip 1: Always Descend From an #id</h4>
<p>&nbsp;</p>
<p>The fastest selector in jQuery is the ID selector (<code>$('#someid')</code>). This is because it maps directly to a native JavaScript method, <code>getElementById()</code>.<br />
<h5>&nbsp;</h5>
<h5>Selecting Single Elements</h5>
<p>&nbsp;</p>
<pre><font color="#804000">&lt;div id="content"&gt;
	&lt;form method="post" action="/"&gt;
		&lt;h2&gt;Traffic Light&lt;/h2&gt;
		&lt;ul id="traffic_light"&gt;
			&lt;li&gt;&lt;input type="radio" class="on" name="light" </font></pre>
<pre><font color="#804000">                          value="red" /&gt; Red&lt;/li&gt;
			&lt;li&gt;&lt;input type="radio" class="off" name="light"</font></pre>
<pre><font color="#804000">                       value="yellow" /&gt; Yellow&lt;/li&gt;
			&lt;li&gt;&lt;input type="radio" class="off" name="light" </font></pre>
<pre><font color="#804000">                            value="green" /&gt; Green&lt;/li&gt;
		&lt;/ul&gt;
		&lt;input class="button" id="traffic_button" type="submit" </font></pre>
<pre><font color="#804000">              value="Go" /&gt;
	&lt;/form&gt;
&lt;/div&gt;</font></pre>
<pre></pre>
<p>Selecting the button like this is slower:
<pre>var traffic_button = $('#content .button');</pre>
<p>Instead, select the button directly:
<pre>var traffic_button = $('#traffic_button');</pre>
<pre>&nbsp;</pre>
<pre></pre>
<h5>Selecting Multiple Elements</h5>
<p>Once we start talking about selecting multiple elements, we are really talking about DOM traversal and looping, something that is slow.</p>
<p>To minimize the performance hit, <b>always descend from the closest parent ID</b>:
<pre>var traffic_lights = $('#traffic_light input');</pre>
<pre>&nbsp;</pre>
<h4>jQuery Performance Tip 2: Use Tags Before Classes</h4>
<p>&nbsp;</p>
<p>The second fastest selector in jQuery is the Tag selector (<code>$('head')</code>). Again, this is because it maps to a native JavaScript method, <code>getElementsByTagName()</code>.</p>
<p>&nbsp;
<pre><font color="#804000">&lt;div id="content"&gt;
	&lt;form method="post" action="/"&gt;
		&lt;h2&gt;Traffic Light&lt;/h2&gt;
		&lt;ul id="traffic_light"&gt;
			&lt;li&gt;&lt;input type="radio" class="on" name="light" </font></pre>
<pre><font color="#804000">                             value="red" /&gt; Red&lt;/li&gt;
			&lt;li&gt;&lt;input type="radio" class="off" name="light" </font></pre>
<pre><font color="#804000">                        value="yellow" /&gt; Yellow&lt;/li&gt;
			&lt;li&gt;&lt;input type="radio" class="off" name="light" </font></pre>
<pre><font color="#804000">                     value="green" /&gt; Green&lt;/li&gt;
		&lt;/ul&gt;
		&lt;input class="button" id="traffic_button" type="submit" </font></pre>
<pre><font color="#804000">               value="Go" /&gt;
	&lt;/form&gt;
&lt;/div&gt;</font></pre>
<pre><font color="#804000">
</font></pre>
<p>Always prefix a class with a tag name (and remember to descend from an ID):
<pre>var active_light = $('#traffic_light input.on');</pre>
<pre>&nbsp;</pre>
<p><i>Note: The class selector is among the slowest selectors in jQuery; in IE it loops through the entire DOM. Avoid using it whenever possible.</i></p>
<p>&nbsp;
<p>Never prefix an ID with a tag name. For example, this is slow because it will loop through all <code>&lt;div&gt;</code> elements looking for the ‘content’ ID:</p>
<p>&nbsp;
<pre>var content = $('div#content');</pre>
<pre>
</pre>
<p>Along the same lines, it is redundant to descend from multiple IDs:
<pre>var traffic_light = $('#content #traffic_light');</pre>
<pre>&nbsp;</pre>
<h4>jQuery Performance Tip 3: Cache jQuery Objects</h4>
<p>&nbsp;</p>
<p>Get in the habit of saving your jQuery objects to a variable (much like our examples above).</p>
<p>For example, never (eeeehhhhver) do this:
<pre>$('#traffic_light input.on).bind('click', function(){...});
$('#traffic_light input.on).css('border', '3px dashed yellow');
$('#traffic_light input.on).css('background-color', 'orange');
$('#traffic_light input.on).fadeIn('slow');</pre>
<p>Instead, first save the object to a local variable, and continue your operations:
<pre>var $active_light = $('#traffic_light input.on');
$active_light.bind('click', function(){...});
$active_light.css('border', '3px dashed yellow');
$active_light.css('background-color', 'orange');
$active_light.fadeIn('slow');</pre>
<pre>&nbsp;</pre>
<pre></pre>
<p><i>Tip: Since we want to remember that our local variable is a jQuery wrapped set, we are using $ as a prefix.</i></p>
<p><em></em>&nbsp;
<p>Remember, <b>never repeat a jQuery selection operation</b> more than once in your application.</p>
<p>&nbsp;<br />
<h5>Bonus Tip &#8211; Storing jQuery results for later</h5>
<p>&nbsp;</p>
<p>If you intend to use the jQuery result object(s) in another part of your program, or should your function execute more than once, cache it in an object with a <a href="http://www.webdevelopersnotes.com/tutorials/javascript/global_local_variables_scope_javascript.php3">global scope</a>.</p>
<p>&nbsp;
<p>By defining a global container with jQuery results, we can reference them from within other functions:</p>
<p>&nbsp;
<pre><font color="#804000">// Define an object in the global scope (i.e. the window object)
window.$my =
{
	// Initialize all the queries you want to use more than once
	head : $('head'),
	traffic_light : $('#traffic_light'),
	traffic_button : $('#traffic_button')
};

function do_something()
{
	// Now you can reference the stored results and manipulate them
	var script = document.createElement('script');
	$my.head.append(script);

	// When working inside functions, continue to save jQuery results
	// to your global container.
	$my.cool_results = $('#some_ul li');
	$my.other_results = $('#some_table td');

	// Use the global functions as you would a normal jQuery result
	$my.other_results.css('border-color', 'red');
	$my.traffic_light.css('border-color', 'green');
}</font></pre>
<pre></pre>
<h4>jQuery Performance Tip 4: Harness the Power of Chaining</h4>
<p>&nbsp;</p>
<p>The previous example can also be accomplished like this:</p>
<p>&nbsp;
<pre><font color="#804000">var $active_light = $('#traffic_light input.on');</font></pre>
<pre><font color="#804000">$active_light.bind('click', </font></pre>
<pre><font color="#804000"> function(){...})
	.css('border', '3px dashed yellow')
	.css('background-color', 'orange')
	.fadeIn('slow');</font></pre>
<pre>&nbsp;</pre>
<p>This allows us to write less code, making our JavaScript more lightweight.</p>
<p>&nbsp;<br />
<h4>jQuery Performance Tip 5:&nbsp; Use Sub-queries</h4>
<p>jQuery allows us to run additional selector operations on a wrapped set. This reduces performance overhead on subsequent selections since we already grabbed and stored the parent object in a local variable.</p>
<p>&nbsp;
<pre><font color="#804000">&lt;div id="content"&gt;
	&lt;form method="post" action="/"&gt;
		&lt;h2&gt;Traffic Light&lt;/h2&gt;
		&lt;ul id="traffic_light"&gt;
			&lt;li&gt;&lt;input type="radio" class="on" name="light" </font></pre>
<pre><font color="#804000">                        value="red" /&gt; Red&lt;/li&gt;
			&lt;li&gt;&lt;input type="radio" class="off" name="light" </font></pre>
<pre><font color="#804000">                       value="yellow" /&gt; Yellow&lt;/li&gt;
			&lt;li&gt;&lt;input type="radio" class="off" name="light" </font></pre>
<pre><font color="#804000">                   value="green" /&gt; Green&lt;/li&gt;
		&lt;/ul&gt;
		&lt;input class="button" id="traffic_button" type="submit" value="Go" /&gt;
	&lt;/form&gt;
&lt;/div&gt;</font></pre>
<pre>&nbsp;</pre>
<p>For example, we can leverage sub-queries to grab the active and inactive lights and cache them for later manipulation.</p>
<p>&nbsp;
<pre><font color="#804000">var $traffic_light = $('#traffic_light'),
	$active_light = $traffic_light.find('input.on'),
	$inactive_lights = $traffic_light.find('input.off');</font></pre>
<pre>&nbsp;</pre>
<p><i>Tip: You can declare multiple local variables by separating them with commas – save those bytes!</i></p>
<p><em></em>&nbsp;<br />
<h4>jQuery Performance Tip 6: Limit Direct DOM Manipulation</h4>
<p>&nbsp;</p>
<p>The basic idea here is to create exactly what you need in memory, and <b>then</b> update the DOM. This is not a jQuery best practice, but a must for efficient JavaScript. <a href="http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip6">Direct DOM manipulation is slow</a>.</p>
<p>&nbsp;
<p>For example, if you need to dynamically create a list of elements, do not do this:</p>
<p>&nbsp;
<pre><font color="#804000">var top_100_list = [...], // assume this has 100 unique strings
$mylist = $('#mylist'); // jQuery selects our &lt;ul&gt; element

for (var i=0, l=top_100_list.length; i&lt;l; i++)
{
	$mylist.append('&lt;li&gt;' + top_100_list[i] + '&lt;/li&gt;');
}</font></pre>
<pre></pre>
<p>Instead, we want to create the entire set of elements in a string before inserting into the DOM:</p>
<p>&nbsp;
<pre><font color="#804000">var top_100_list = [...], // assume this has 100 unique strings
$mylist = $('#mylist'), // jQuery selects our &lt;ul&gt; element
top_100_li = ""; // This will store our list items

for (var i=0, l=top_100_list.length; i&lt;l; i++)
{
	top_100_li += '&lt;li&gt;' + top_100_list[i] + '&lt;/li&gt;';
}</font></pre>
<pre><font color="#804000">$mylist.html(top_100_li);</font></pre>
<pre><font color="#804000"></font>
</pre>
<p>Even faster, we should <b>always wrap many elements</b> in a single parent node before insertion:</p>
<p>&nbsp;
<pre><font color="#804000">var top_100_list = [...], // assume this has 100 unique strings
	$mylist = $('#mylist'), // jQuery selects our &lt;ul&gt; element
	top_100_ul = '&lt;ul id="#mylist"&gt;'; </font></pre>
<pre><font color="#804000">// This will store our entire unordered list

for (var i=0, l=top_100_list.length; i&lt;l; i++)
{
	top_100_ul += '&lt;li&gt;' + top_100_list[i] + '&lt;/li&gt;';
}
top_100_ul += '&lt;/ul&gt;'; // Close our unordered list

$mylist.replaceWith(top_100_ul);</font></pre>
<pre><font color="#804000"></font>
</pre>
<p>If you do the above and are still concerned about performance:</p>
<ul>
<li>Give jQuery’s <code>clone()</code> method a try. This creates a copy of the node tree, which you can manipulate “off-line” and then insert back in when you are ready.
<li>
<li>Use <a href="http://www.devguru.com/technologies/xmldom/quickref/obj_documentFragment.html">DOM DocumentFragments</a>. As the <a href="http://ejohn.org/blog/dom-documentfragments/">creator of jQuery points out</a>, they perform much better than direct DOM manipulation. The idea would be to create what you need (similar to what we did above with a string), and use the jQuery <a href="http://docs.jquery.com/Manipulation">insert or replace methods</a>.
<li></li>
</ul>
<h4>jQuery Performance Tip 7:&nbsp; Leverage Event Delegation (a.k.a. Bubbling)</h4>
<p>&nbsp;</p>
<p>Unless <a href="http://docs.jquery.com/Events/jQuery.Event#event.stopPropagation.28.29">told otherwise</a>, every event (e.g. click, mouseover, etc.) in JavaScript “bubbles” up the DOM tree to parent elements. This is incredibly useful when we want many elements (nodes) to call the same function.</p>
<p>Instead of binding an event listener function to many nodes—very inefficient—you can <b>bind it once</b> to their parent, and have it figure out which node triggered the event.</p>
<p>&nbsp;
<p>For example, say we are developing a large form with many inputs, and want to toggle a class name when selected.</p>
<p>&nbsp;
<p>A binding like this is inefficient:</p>
<p>&nbsp;
<pre><font color="#804000">$('#entryform input).bind('focus', function(){
	$(this).addClass('selected');
}).bind('blur', function(){
	$(this).removeClass('selected');
});</font></pre>
<p><font color="#804000">Instead, we should listen for the focus and blur events at the parent level:</font>
<pre><font color="#804000">$('#entryform).bind('focus', function(e){
	var cell = $(e.target);  </font></pre>
<pre><font color="#804000">// e.target grabs the node that triggered the event.
	cell.addClass('selected');
}).bind('blur', function(e){
	var cell = $(e.target);
	cell.removeClass('selected');
});</font></pre>
<pre>&nbsp;</pre>
<p>The parent node acts as a dispatcher and can then do work based on what <a href="http://docs.jquery.com/Events/jQuery.Event#event.target">target element</a> triggered the event.</p>
<p>&nbsp;
<p>If you find yourself binding one event listener to many elements, you are doing something wrong (and slow).</p>
<p>&nbsp;<br />
<h4>jQuery Performance Tip 8: Eliminate Query Waste</h4>
<p>&nbsp;</p>
<p>Although jQuery fails nicely if it does not find any matching elements, it still takes time to look for them. If you have one global JavaScript for your entire site, it may be tempting to throw every one of your jQuery functions into <code>$(document).ready(function(){ // all my glorious code })</code>.</p>
<p>Don’t you dare.</p>
<p>&nbsp;
<p>Only run functions that are applicable to the page. The most efficient way to do this is to use inline initialization functions so your template has full control over when and where JavaScript executes.</p>
<p>For example, in your “article” page template, you would include the following code before the body close:</p>
<p>&nbsp;
<pre><font color="#804000">&lt;script type="text/javascript&gt;
mylib.article.init();
&lt;/script&gt;
&lt;/body&gt;</font></pre>
<pre>&nbsp;</pre>
<p>If your page template includes any variety of modules that may or may not be on the page, or for visual reasons you need them to initialize sooner, you could place the initialization function immediately after the module.</p>
<p>&nbsp;
<pre><font color="#804000">&lt;ul id="traffic_light"&gt;
	&lt;li&gt;&lt;input type="radio" class="on" name="light" value="red" /&gt; Red&lt;/li&gt;
	&lt;li&gt;&lt;input type="radio" class="off" name="light" value="yellow" /&gt; Yellow&lt;/li&gt;
	&lt;li&gt;&lt;input type="radio" class="off" name="light" value="green" /&gt; Green&lt;/li&gt;
&lt;/ul&gt;
&lt;script type="text/javascript&gt;
mylib.traffic_light.init();
&lt;/script&gt;</font></pre>
<pre></pre>
<p>Your Global JS library would look something like this:</p>
<p>&nbsp;
<pre><font color="#804000">var mylib =
{
	article_page :
	{
		init : function()
		{
			// Article page specific jQuery functions.
		}
	},
	traffic_light :
	{
		init : function()
		{
			// Traffic light specific jQuery functions.
		}
	}
}</font></pre>
<pre>&nbsp;</pre>
<h4>jQuery Performance Tip 9: Defer to <code>$(window).load</code></h4>
<h4><code></code>&nbsp;</h4>
<p>There is a temptation among jQuery developers to hook everything into the <code>$(document).ready</code> pseudo event. After all, it is used in most examples you will find.</p>
<p>Although <code>$(document).ready</code> is incredibly useful, it occurs during page render while objects are still downloading. If you notice your page stalling while loading, all those <code>$(document).ready</code> functions could be the reason why.</p>
<p>&nbsp;
<p>You can reduce CPU utilization during the page load by binding your jQuery functions to the <code>$(window).load</code> event, which occurs after all objects called by the HTML (including <code>&lt;iframe&gt;</code> content) have downloaded.</p>
<p>&nbsp;
<pre><font color="#804000">$(window).load(function(){
	// jQuery functions to initialize after the page has loaded.
});</font></pre>
<pre></pre>
<p>Superfluous functionality such as drag and drop, binding visual effects and animations, pre-fetching hidden images, etc., are all good candidates for this technique.</p>
<p>&nbsp;<br />
<h4>jQuery Performance Tip 10: Compress Your JS</h4>
<p>&nbsp;</p>
<p>Okay, this isn’t jQuery related, but I had to include it. There is a tendency to make JavaScript functions and variables overly descriptive, which is essential for developers but irrelevant to users.</p>
<p>No more excuses, it’s time to build JS compression into our workflows. Comment the heck out of your code, and run it through a compression tool before launching to production.</p>
<p>&nbsp;
<p>Use <a href="http://www.julienlecomte.net/yuicompressor/">YUICompressor</a> to squeeze out wasteful bytes from your code. In our experience, it safely compresses JavaScript as small as it can possibly get without a CPU penalty (such as Base62 encoding with <a href="http://dean.edwards.name/packer/">Packer</a>).</p>
<p>&nbsp;
<p><i>Tip: For maximum compression in YUICompressor, always declare your variables (e.g. var my_long_variable_name;).</i></p>
<p><em></em>&nbsp;<br />
<h4>jQuery Performance Tip 11:&nbsp; Learn the Library!</h4>
<p>&nbsp;</p>
<p>Print out this <a href="http://acodingfool.typepad.com/blog/jquery-13-cheat-sheet.html">jQuery 1.3 cheat sheet</a>, and make it a goal to eventually understand what each function does. If you find yourself repeating yourself repeating, there is probably an easier (and more efficient) way. jQuery 1.4 will hopefully be released right around the corner, but this should prove an excellent resource until then.</p>
<p>&nbsp;
<p><a href="http://www.artzstudio.com/files/jquery-rules/jquery_1.3_cheatsheet_v1.pdf"><img height="212" alt="jquery cheat sheet" src="http://www.artzstudio.com/files/jquery-rules/jquery_13_cheatsheet_thumb.jpg" width="336"></a></p>
]]></content:encoded>
			<wfw:commentRss>http://addyosmani.com/blog/11-ways-to-increase-your-jquery-performance/feed/</wfw:commentRss>
		<slash:comments>67</slash:comments>
		</item>
	</channel>
</rss>
