<?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; optimization</title>
	<atom:link href="http://addyosmani.com/blog/tag/optimization/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>31 jQuery Snippets That Will Help Make You A JavaScript Pro</title>
		<link>http://addyosmani.com/blog/31-jquery-snippets/</link>
		<comments>http://addyosmani.com/blog/31-jquery-snippets/#comments</comments>
		<pubDate>Thu, 08 Apr 2010 01:18:59 +0000</pubDate>
		<dc:creator>Addy</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[cheatsheet]]></category>
		<category><![CDATA[Code Samples]]></category>
		<category><![CDATA[improve]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[javascript snippets]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[jquery 1.3.2]]></category>
		<category><![CDATA[jquery 1.4]]></category>
		<category><![CDATA[jquery 1.4.2]]></category>
		<category><![CDATA[jquery clear]]></category>
		<category><![CDATA[jquery lessons]]></category>
		<category><![CDATA[jquery tutorials]]></category>
		<category><![CDATA[optimization]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[samples]]></category>
		<category><![CDATA[snippets]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://addyosmani.com/blog/?p=660</guid>
		<description><![CDATA[&#160;Hey guys. Hopefully if you&#8217;re reading this you&#8217;ve discovered some of the true power jQuery has to offer and you&#8217;re now looking for ways to improve your JavaScript skills even further. There was such a huge response to my last post on jQuery Snippets that I thought it only right to follow up with a [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://addyosmani.com/blog/31-jquery-snippets/"><img width="530" height="342" border="0" alt="" src="http://addyosmani.com/blog/wp-content/uploads/31snip.jpg" /></a></p>
<p>&nbsp;Hey guys. Hopefully if you&#8217;re reading this you&#8217;ve discovered some of the true power jQuery has to offer and you&#8217;re now looking for ways to improve your JavaScript skills even further.</p>
<p>There was such a huge response to my last <a href="http://addyosmani.com/blog/50-jquery-snippets-for-developers/">post</a> on jQuery Snippets that I thought it only right to follow up with a fresh list that focuses on some of the more recent features introduced in jQuery 1.4.x. Because it&#8217;s always useful to have a second pair of eyes look over your code, I asked <a href="http://paulirish.com/">Paul Irish</a> from the jQuery Team to take a look at all of today&#8217;s snippets and he&#8217;s included some useful optimizations to a few of the snippets which I&#8217;ve intregated.</p>
<p><span id="more-660"></span></p>
<p>Now, if I only we could fit Paul into a useful Browser plugin, all my articles would be just as sensible <img src='http://addyosmani.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  The snippets from today can be applied to a wide range of projects so remember to bookmark the post if you find it useful so you can easily come back to it anytime you want. So without further adieu, I give you today&#8217;s 31 Snippets that will help make you a JavaScript Pro.</p>
<p>
<style type="text/css">
  #tiplist { list-style-type: decimal; }
 h1,h2 { font-family:Georgia;}
</style>
</p>
<div>&nbsp;</div>
<ul id="tiplist">
<li>
<h2>Did you know that using jQuery&#8217;s .live() function is more optimal for adding click functions than using .click()? It even handles dynamic content well.</h2>
<pre class="javascript" name="code">
$('.clickme').live('click', function() {
  // Live handler called.
});
</pre>
</li>
<li>
<h2>Attributes in jQuery &#8211; jQuery supports passing attributes for an object as the second argument to the jQuery function itself. This creates a new link on the page:</h2>
<pre class="javascript" name="code">
   $('', {
   text: 'jQuery is awesome!',
   href: 'http://www.jquery.com',
   id: 'someAwesomeID',
   rel: 'external',
   title: 'This is a title'
   }).appendTo('body');
</pre>
</li>
<li>
<h2>Function Grouping &#8211; jQuery supports binding functions so that they can all be defined within the same group. This can be useful for keeping your cody tidy among other things!</h2>
<pre class="javascript" name="code">
jQuery('#foo').bind({
    click: function() {
        // do something
    },
    mouseover: function() {
        // do something
    },
    mouseout: function() {
        // do something
    }
})
</pre>
</li>
<li>
<h2>Have you ever wanted to convert your JSON string into a JavaScript Object? Rather than having to custom code your own function to do it, just use jQuery&#8217;s built in .parseJSON function to achieve this easily (jQuery 1.4.1 and above):</h2>
<pre class="javascript" name="code">
var obj = jQuery.parseJSON('
    {&quot;name&quot;:&quot;Larry King&quot;,
     &quot;age&quot;: &quot;5000&quot;
    }');
alert( obj.name === &quot;Larry King&quot; ); //true
alert (obj.age  === &quot;50&quot;);//false
alert (obj.age  === &quot;5000&quot;); //true
</pre>
</li>
<li>
<h2>Ever since jQuery 1.4 you&#8217;ve been able to use a jQuery feature equivalent to PHP&#8217;s sleep() called delay. If you would like to delay and animated effect all you need to do is use delay as follows:</h2>
<pre class="javascript" name="code">
$('#myJaw').slideUp(300).delay(800).fadeIn(400);
 </pre>
</li>
<li>
<h2>When styling a large number of elements, instead of using css() it is more efficient to append a style tag to the DOM as follows:</h2>
<pre class="javascript" name="code">
$('
<style type="text/css"> div.class { color: red; } </style>

')
.appendTo('head');
</pre>
</li>
<li>
<h2>Here&#8217;s how you can remove the parent elements of any object using jQuery&#8217;s .unwrap() function</h2>
<pre class="javascript" name="code">
/* here we locate any paragraph elements and then
'unwrap' the parent elements around them. These
could be other divs, spans or anything really */

jQuery('p').unwrap();  
</pre>
</li>
<li>
<h2>Would you like to perform an action when an element or its contents gain focus? Here&#8217;s how to do it:</h2>
<pre class="javascript" name="code">
jQuery('form')
    .focusin(function(){
        jQuery(this).addClass('focused');
    });
    .focusout(function(){
        jQuery(this).removeClass('focused');
    });

//However, the preferred way to do this is using
// .focus() and .blur()

//For when an element loses it's focus use .blur()
$('#target').blur(function() {
  alert('Handler for .blur() called.');
});

//For when an element gains focus use .focus()
$('#target').focus(function() {
  alert('Handler for .focus() called.');
});
</pre>
</li>
<li>
<h2>Each traversal method in jQuery creates a new set which builds a stack. You can use .end() to reach the previous set.</h2>
<pre class="javascript" name="code">
$(&quot;
<ul>
<li>&nbsp;</li>
</ul>

&quot;) // li
  .find(&quot;a&quot;) // a
    .attr(&quot;href&quot;, &quot;http://www.google.com/&quot;) // a
    .html(&quot;Google!&quot;) // a
  .end() // li
  .appendTo(&quot;ul&quot;);
  </pre>
</li>
<li>
<h2>I&#8217;ve mentioned this a few times before, but it&#8217;s a feature that many developers forget exists within jQuery &#8211; data() &#8211; jQuery actually has an API for invisibly storing data on DOM nodes so you can easily store any information through JS and it&#8217;ll be available through the same central resource</h2>
<pre class="javascript" name="code">
$(&quot;div&quot;).data(&quot;myName&quot;, 'addy');
$(&quot;div&quot;).data(&quot;myName&quot;) === 'addy';
</pre>
</li>
<li>
<h2>Garbage collection of data stored can either be done through removeData() or via the remove() function after the element has been deleted.</h2>
<pre class="javascript" name="code">
/* Here are two ways to remove all of the information
bound to an element*/
$(&quot;div&quot;).removeData();
$(&quot;div&quot;).remove();
</pre>
</li>
<li>
<h2>Have you ever tried writing a plugin and run into a problem with overriding specific behaviours?. In jQuery you can override the values set or retrieved on the data method by binding to getData and setData.Returning a value will set/return a totally different result.</h2>
<pre class="javascript" name="code">
$(&quot;div&quot;).bind(&quot;getData.value&quot;, function()
{
  return myPlugin.realValue;
});
</pre>
</li>
<li>
<h2>jQuery supports namespacing and this includes namespacing data. You can scope your namespaces to a specific name or plugin and this can help you avoid conflicts with other code that might use the same data name.</h2>
<pre class="javascript" name="code">
/*
Why namespace? Namespacing ensures that your
variables don't conflict with any others which
happen to have the same name. This is important
if you want to avoid your code breaking when
other files or plugins are included in your
page's architecture. See below for an example of
namespacing data.
*/

$(&quot;div&quot;).data(&quot;events.plugin&quot;,
{
   //your data here
 });
</pre>
</li>
<li>
<h2>Looking for a way to namespace your event handlers?. This sample will show you his. It makes it easier to locate your namespace binding later on and easily remove the handler if needed.</h2>
<pre class="javascript" name="code">
$(&quot;div&quot;).bind(&quot;click.plugin&quot;, someFn);
$(&quot;div&quot;).bind(&quot;focus.plugin&quot;, otherFn);
$(&quot;div&quot;).unbind(&quot;.plugin&quot;);
</pre>
</li>
<li>
<h2>You can bind to almost any event and there aren&#8217;t really any limits on what you can or can&#8217;t bind to.</h2>
<pre class="javascript" name="code">
$(&quot;div&quot;).bind(&quot;myplugin&quot;, someFn);
$(&quot;div&quot;).trigger(&quot;myplugin&quot;);
</pre>
</li>
<li>
<h2>A good tip for complicated applications: Custom events are a useful way for multiple pieces of code to bind to the same functionality, so you trigger one event but lots of handlers can be executed.</h2>
<pre class="javascript" name="code">
$(&quot;div&quot;).bind(&quot;remove.pluginA&quot;, someFn);
$(&quot;div&quot;).bind(&quot;remove.pluginB&quot;, otherFn);
$(&quot;div&quot;).trigger(&quot;remove&quot;);
</pre>
</li>
<li>
<h2>Have you been trying to find a way to listen to events from a particular context? The delegate and undelegate methods make this possible (supported in jQuery 1.4.2 onwards). There&#8217;s also a very large performance gain got from switching over to .delegate()!</h2>
<pre class="javascript" name="code">
$(&quot;table&quot;).delegate(&quot;td&quot;, &quot;hover&quot;, function(){
  $(this).toggleClass(&quot;active&quot;);
});
</pre>
</li>
<li>
<h2>You can dynamically change the context of a function (if needed) using something similar to this. Since jQuery 1.4.* you&#8217;ve also been able to easily remove the proxied function.</h2>
<pre class="javascript" name="code">
var obj = { method: function(){} };
$(&quot;#foo&quot;).click( jQuery.proxy( obj, &quot;method&quot; ) );
$(&quot;#foo&quot;).unbind( &quot;click&quot;, obj.method );
</pre>
</li>
<li>
<h2>Interested in creating a simple custom selector?. Creating your own selectors is easy and you can do this for your plugins if you would like some easy querying features.</h2>
<pre class="javascript" name="code">
jQuery.expr[&quot;:&quot;].myplugin = function(elem) {
  return !!jQuery.data(&quot;myplugin&quot;);
};
</pre>
</li>
<li>
<h2>Did you know that you can treat jQuery objects like arrays?. Take a look at this example.</h2>
<pre class="html" name="code">
/*Here's some sample HTML followed by some jQuery
that allows us to access the values of any &quot;box&quot;
by index.*/
<div id="wrapper">
<div class="box">Content #1!</div>
<div class="box">Content #2!</div>
<div class="box">Content #3!</div>
<div class="box">Content #4!</div>
</div>
<div id="wrapper2">
<div class="box">Content2 #1!</div>
</div>
</pre>
</li>
<pre class="javascript" name="code">

// returns 4
$('#wrapper .box').length;

// num is equal to 4
var num = $('#wrapper .box');
num = num.length;

// text is equal to 'Content #2!'
var text = $(&quot;#wrapper .box&quot;)[1];

// text is equal to 'Content #1'
var text = $(&quot;#wrapper .box&quot;)[0];

// text is equal to 'Content2 #1'
var text = $(&quot;#wrapper2 .box&quot;)[0];
</pre>
<li>
<h2>Selection storage: Did you know that you can store the results from a jQuery selection in a variable and *still* have access to the same methods?. Here&#8217;s a useful example.</h2>
<pre class="javascript" name="code">
var $myBox = $('#test');
/*the variable myHTML is equal to the content's of
'#test'*/
var myHTML = $myBox.html();
</pre>
</li>
<li>
<h2>Did you know that jQuery has great support for Callbacks? Here are two ways you can tell if a function has completed running.</h2>
<pre class="javascript" name="code">
function runAlertNow ()
{
	$(this).html('I just ran this function!');
}

// both of these lines do the same thing
$('#test').slideUp(400, runAlertNow);
$('#test').slideUp(400, function ()
{
$(this).html('I just ran the anonymous function!');
});
</pre>
</li>
<li>
<h2>Very useful tip: Did you know that you can select elements within another element just by passing a second parameter to the jQuery initializer?</h2>
<pre class="html" name="code">
<div id="yourparent">
<div id="mychild">&nbsp;</div>
</div>
</pre>
</li>
<p>    Here are three ways to access an element within an element:</p>
<pre class="javascript" name="code">
$('#yourparent').find('#mychild')
//or even shorter:
$('#mychild', $('#yourparent'))
//or even shorter:
$('#mychild', '#yourparent')
</pre>
<li>
<h2>How do you handle access to elements with IDs that contain special characters in jQuery?</h2>
<pre class="javascript" name="code">
$(&quot;$some[id]&quot;).show(); // won't work for this type of ID
$(&quot;$some\\[id\\]&quot;).show() // works fine for the ID: some[id]
</pre>
</li>
<li>
<h2>How do you enable or disable form elements within jQuery?</h2>
<pre class="javascript" name="code">
//To disable a form element such as a text input field
$(&quot;#myelement&quot;).attr(&quot;disabled&quot;, &quot;disabled&quot;);

//To re-enable a disabled form element
$(&quot;#myelement&quot;).removeAttr(&quot;disabled&quot;);
</pre>
</li>
<li>
<h2>How do you check if something exists in the DOM using jQuery:</h2>
<pre class="javascript" name="code">
/*The .length property in jQuery returns the length
or number of elements inside an array or the string
length. If you want to check the existence of the
element, just check if the returned value of length
is zero:*/

if ($(selector).length)
{
   //your code here
}
</pre>
</li>
<li>
<h2>How do you search all the nodes on a page for a particular piece of text using jQuery?</h2>
<pre class="javascript" name="code">
/*This useful extended function will allow you to
pattern match a keyword across all the nodes in a
page. See the example below for how GMail use something
similar in concept for their search-keyword highlighting*/

$.fn.egrep = function(pat) {
 var out = [];
 var textNodes = function(n) {
  if (n.nodeType == Node.TEXT_NODE) {
   var t = typeof pat == 'string' ?
    n.nodeValue.indexOf(pat) != -1 :
    pat.test(n.nodeValue);
   if (t) {
    out.push(n.parentNode);
   }
  }
  else {
   $.each(n.childNodes, function(a, b) {
    textNodes(b);
   });
  }
 };
 this.each(function() {
  textNodes(this);
 });
 return out;
};

// Here's an example of using this to highlight
//all the nodes on the page that contain the keyword
//'jQuery'
$(&quot;#testbutton&quot;).click(function()
{
var n = $('body').egrep(/jquery/i);
for (var i = 0; i &lt; n.length; ++i)
{
   void($(n[i]).css('background', 'yellow'));
 }
});
</pre>
</li>
<li>
<h2>Have you ever wanted to retain any of the information .remove() strips from the DOM? The .detach() method is a lot like remove() except that .detach() keeps all jQuery data associated with the removed elements. This is useful when you want to reinsert removed elements into the DOM later.</h2>
<pre class="javascript" name="code">
//In the below example
$(&quot;p&quot;).click(function(){
      $(this).toggleClass(&quot;off&quot;);
    });
    var p;
    $(&quot;button&quot;).click(function(){
      if ( p ) {
        p.appendTo(&quot;body&quot;);
        p = null;
      } else {
        p = $(&quot;p&quot;).detach();
      }
    });
</pre>
</li>
<li>
<h2>You can easily find the closest element to another (beginning at the current element and moving up the DOM) using .closest(). See the below example:</h2>
<pre class="javascript" name="code">
$(document).ready(function()
{
//Let's set the background color of the nearest
//UL in this pseudo-menu
$('li.subchild').closest('ul').css('background-color', 'red');
});
</pre>
<pre class="html" name="code">
<ul>
<li>Parent Menu
<ul>
<li class="subchild">Child Item 1</li>
<li class="subchild">Child Item 2</li>
</ul>
</li>
</ul>
</pre>
</li>
<li>
<h2>How to easily and quickly add one-click clearing of default input text values from your fields</h2>
<pre class="javascript" name="code">
(function($){
	$.fn.clearDefault = function(){
		return this.each(function(){
			var default_value = $(this).val();
			$(this).focus(function(){
				if ($(this).val() == default_value)
                              $(this).val(&quot;&quot;);
			});
			$(this).blur(function(){
				if ($(this).val() == &quot;&quot;)
                              $(this).val(default_value);
			});
		});
	};
})(jQuery);

// How to use it: $('input').clearDefault();
</pre>
</li>
<li>
<h2>Would you like to style only a particular range of elements within a list? jQuery&#8217;s .slice() function makes this possible through indices</h2>
<pre class="html" name="code">
<ul>
<li>Apples</li>
<li>Pears</li>
<li>Cherries</li>
<li>Grapes</li>
<li>Mangos</li>
</ul>
</pre>
<pre class="javascript" name="code">
  /*If we just want to set the background-color of
    everything after element number two (pears) we
   can do this using:*/

	$('li').slice(2).css('background-color', 'yellow');

 /*and if we want to set the bg-color of the elements
   after two(pears), but only up to and including 4
   (grapes), we can use:*/
   $('li').slice(2, 4).css('background-color', 'green')
</pre>
</li>
<p>I hope you found those useful!. If so, feel free to hit the <a href="http://addyosmani.com/blog/31-jquery-snippets/" class="retweet">31 jQuery Snippets That Will Make You A JavaScript Pro (via @addyosmani)</a>button so you can share it with all your friends and colleagues.</p>
<p>Good luck with your JavaScript!</p>
<p>- Addy</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://addyosmani.com/blog/31-jquery-snippets/feed/</wfw:commentRss>
		<slash:comments>37</slash:comments>
		</item>
		<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>
