10 Ways to Instantly Increase Your jQuery Performance

10 Ways to Instantly Increase Your jQuery Performance

This article will present ten easy steps that will instantly improve your script’s performance. Don’t worry; there isn’t anything too difficult here. Everyone can apply these methods! When you’re finished reading, please let us know your speed tips.

1. Always Use the Latest Version

jQuery is in constant development and improvement. John and his team are always researching new ways to improve program performances.
As a sidenote, just a few months ago, he released Sizzle, a selector library that’s said to improve program performances up to 3 times in Firefox.

If you want to stay up to date without having to download the library a thousand times, GIYF (Google Is Your Friend), in this situation too. Google provides a lot of Ajax libraries from which to choose.

	<!-- get the API with a simple script tag -->
	<script type="text/javascript" src="http://www.google.com/jsapi"></script>
	<script type="text/javascript">
		/* and load minified jQuery v1.3.2 this way */
		google.load ("jquery", "1.3.2", {uncompressed: false});
		
		/* this is to display a message box
		   when the page is loaded */
		function onLoad () {
			alert ("jQuery + Google API!");
		}
		
		google.setOnLoadCallback (onLoad);
	</script>

* Editor’s Note: Perhaps, the quicker and easier method is to simply link to the script directly. Rather than hard-coding the specific version of jQuery directly (1.3.2), you should instead use 1, which will automatically reference the most recent version of the library.

	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>

2. Combine and Minify Your Scripts

Minify

The majority of browsers are not able to process more than one script concurrently so they queue them up — and load times increase.
Assuming the scripts are to be loaded on every page of your website, you should consider putting them all into a single file and use a compression tool (such as Dean Edwards’) to minify them. Smaller file sizes equal faster load times.

The goal of JavaScript and CSS minification is always to preserve the operational qualities of the code while reducing its overall byte footprint (both in raw terms and after gzipping, as most JavaScript and CSS served from production web servers is gzipped as part of the HTTP protocol). — From YUI compressor, an excellent tool jQuery officially reccomends to minify scripts.

3. Use For Instead of Each

Native functions are always faster than any helper counterparts.
Whenever you’re looping through an object received as JSON, you’d better rewrite your JSON and make it return an array through which you can loop easier.

Using Firebug, it’s possible to measure the time each of the two functions takes to run.

	var array = new Array ();
	for (var i=0; i<10000; i++) {
		array[i] = 0;
	}
	
	console.time('native');
	var l = array.length;
	for (var i=0;i<l; i++) {
		array[i] = i;
	}
	console.timeEnd('native');
	
	console.time('jquery');
	$.each (array, function (i) {
		array[i] = i;
	});
	console.timeEnd('jquery');

The above results are 2ms for native code, and 26ms for jQuery’s “each” method. Provided I tested it on my local machine and they’re not actually doing anything (just a mere array filling operation), jQuery’s each function takes over 10 times as long as JS native “for” loop. This will certainly increase when dealing with more complicated stuff, like setting CSS attributes or other DOM manipulation operations.

4. Use IDs Instead of Classes

It’s much better to select objects by ID because of the library’s behavior: jQuery uses the browser’s native method, getElementByID(), to retrieve the object, resulting in a very fast query.

So, instead of using the very handy class selection technique, it’s worth using a more complex selector (which jQuery certainly doesn’t fail to provide), write your own selector (yes, this is possible, if you don’t find what you need), or specify a container for the element you need to select.

	// Example creating a list and filling it with items
	//  and selecting each item once
	
	console.time('class');
	var list = $('#list');
	var items = '<ul>';
	
	for (i=0; i<1000; i++) {
		items += '<li class="item' + i + '">item</li>';
	}
	
	items += '</ul>';
	list.html (items);
	
	for (i=0; i<1000; i++) {
		var s = $('.item' + i);
	}
	console.timeEnd('class');

	console.time('id');
	var list = $('#list');
	var items = '<ul>';
	
	for (i=0; i<1000; i++) {
		items += '<li id="item' + i + '">item</li>';
	}
	
	items += '</ul>';
	list.html (items);
	
	for (i=0; i<1000; i++) {
		var s = $('#item' + i);
	}
	console.timeEnd('id');

The above code really shows the differences between the two ways of selecting elements, highlighting a never-ending over 5 seconds time to load the class driven snippet.

5. Give your Selectors a Context

As stated in jQuery’s documentation,

The DOM node context originally passed to jQuery() (if none was passed then context will be equal to the document).
It should be used in conjunction with the selector to determine the exact query used.

So, if you must use classes to target your elements, at least prevent jQuery from traversing the whole DOM using selectors appropriately.

Instead of

	$('.class').css ('color' '#123456');

always go for contextualized selectors in the form:

	$(expression, context)

thus yielding

	$('.class', '#class-container').css ('color', '#123456');

which runs much faster, because it doesn’t have to traverse the entire DOM — just the #class-container element.

6. Cache. ALWAYS.

Do not make the mistake or reusing your selectors time and time again. Instead, you should cache it in a variable. That way, the DOM doesn’t have to track down your element over and over again.

Never select elements multiple times inside a loop EVER! It’d be a speed-killer!

	$('#item').css ('color', '#123456');
	$('#item').html ('hello');
	$('#item').css ('background-color', '#ffffff');
	
	// you could use this instead
	$('#item').css ('color', '#123456').html ('hello').css ('background-color', '#ffffff');
	
	// or even
	var item = $('#item');
	item.css ('color', '#123456');
	item.html ('hello');
	item.css ('background-color', '#ffffff');
	
	
	// as for loops, this is a big no-no
	console.time('no cache');
	for (var i=0; i<1000; i++) {
		$('#list').append (i);
	}
	console.timeEnd('no cache');
	
	// much better this way
	console.time('cache');
	var item = $('#list');
	
	for (var i=0; i<1000; i++) {
		item.append (i);
	}
	console.timeEnd('cache');

And, as the following chart exemplifies, the results of caching are evident even in relatively short iterations.

7. Avoid DOM Manipulation

DOM manipulation should be as limited as possible, since insert operations like prepend(), append(), after() are rather time-consuming.

The above example could be quickened using html() and building the list beforehand.

	var list = '';
	
	for (var i=0; i<1000; i++) {
		list += '<li>'+i+'</li>';
	}
	
	('#list').html (list);

8. No String concat(); Use join() for Longer Strings

It might appear strange, but this really helps to speed things, especially when dealing with long strings of text that need to be concatenated.

First create an array and fill it with what you have to join together. The join() method will prove much faster than the string concat() function.

	var array = [];
	for (var i=0; i<=10000; i++) {
	    array[i] = '<li>'+i+'</li>';
	}

	$('#list').html (array.join (''));

However, recent tests conducted by Tom Trenka contributed to the creation of the following chart.

“The += operator is faster—even more than pushing string fragments into an array and joining them at the last minute” and “An array as a string buffer is more efficient on all browsers, with the exception of Firefox 2.0.0.14/Windows, than using String.prototype.concat.apply.” — Tom Trenka

9. Return False

You may have noticed whenever your functions don’t return false, you jump to the top of the page.
When dealing with longer pages, this result can be quite annoying.

So, instead of

	$('#item').click (function () {
		// stuff here
	});

take the time to write

	$('#item').click (function () {
		// stuff here
		return false;
	});

10. Bonus tip – Cheat-sheets and Library References

This isn’t a speed up tip, but could end up, in a round about way, being one if you take the time to find your way through cheatsheets and function references.
Save yourself some time and keep a cheat-sheet within an arm’s reach.


Tags: jQuery
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • kramer

    As of 1.4.2, #3 is actually false, i.e. each() is faster, at least on my machine.

  • Micha

    I wonder if there is a difference in performance between this:
    $(‘.class’, ‘#class-container’).css (‘color’, ‘#123456′);

    and that:
    $(‘#class-container .class’).css (‘color’, ‘#123456′);

    Any suggestions?

    • http://www.bobsp.de Boris

      I’ve read that there is a difference. Maybe you should take a look at this

      http://net.tutsplus.com/tutorials/javascript-ajax/how-jquery-beginners-can-test-and-improve-their-code/

      at #3.

      Boris

    • http://www.neteffectservices.com Ryan Wheale

      $(‘.class’, ‘#someID’) is merely a shortcut for $(‘#someID’).find(‘.class’) – so no matter what, you are better off using find() as opposed to the context parameter. By using find(), you are eliminating a function call… which is always good ;)

    • http://bfred.it Federico / Bfred.it

      As expected, in my test #5 is plain wrong. See for yourself:

      The general rule is, the less selectors, the better. I thought of the opposite until recently, but that’s true.

  • Mark Davenport

    This is really great! Improved the performance of one of my functions dramatically. Thanks.

  • me
  • http://seobynova.com/ Tư vấn seo

    Thanks for share infomations

  • fukid

    somehow #3 is not corrent now in chrome 7 and firefox 3.6
    chrome 7:

    var array = new Array ();
    for (var i=0; i<10000; i++) {
    array[i] = 0;
    }

    console.time('native');
    var l = array.length;
    for (var i=0;i<l; i++) {
    array[i] = i;
    }
    console.timeEnd('native');

    console.time('jquery');
    $.each (array, function (i) {
    array[i] = i;
    });
    console.timeEnd('jquery');
    native: 24ms
    jquery: 7ms

    firefox 3.6:
    native: 15ms
    jquery: 12ms

    • http://www.jobsboard.co.nz Andrew

      and in Chrome 13

      native: 15ms
      jquery: 3ms

  • Shoggie

    Hi all, thank you for sharing!

    Here’s a nice one is ran into today:

    $(“#inSight-content-Search”).hide().html(content).fadeIn();

    That’s a div that gets stuffed with approx 3.2 MB of HTML data from an XSL transformation.

    Adding the .hide() method cuts back the waiting time by 7 (!) seconds in my enviroment.

    Cheers!

  • http://digitalrenewal.com Trisha

    This is great! following your guide, many of the elements are already written correctly so Im pretty good to start with. a question though if anyone knows the answer…

    I’ve added a jquery slider to a page template in wordpress. It was loading perfectly until I realized that I’d installed it incorrectly, linking to google’s latest jquery version then adding custom scripts BEFORE the wp-head tag. (as soon as you install a plugin with jquery, it breaks the slider in this order)

    When I corrected the tag order (enqueue jquery, then wp-head, then custom scripts) I get a lag in load time. It loads all of the content on the page first, then the slider pops up seeming out of nowhere. Its driving me batty. If the server has any delay at all, its really noticeable. I’ve tested loading the scripts in many ways and added a compression plugin, but I still get that lag.

    So my question is… is there any way to FORCE jquery to load first on the page or at least prior to the wordpress content???

    Thanks so much!

    • http://digitalrenewal.com Trisha

      I finally figured this out when i noticed that my ‘images were gone’…
      The css was pointing to images inside the slider that weren’t there. As soon as i relinked the images, it fixed the problem. In the meantime I learned alot about the best ways to utilitze jquery and optimize its usage, so THANK YOU! :D

      • ankit

        HI Trisha is have question….
        that we are always using jquery.min file and jquery.ui file
        in this files the lots of function are created but you have any idea how to create jquery.min file if i wish to create it by my self.

  • http://www.blainesch.com BlaineSch

    The “return false” part at the bottom only helps if it’s a “click” event. You should be passing the event and calling that event function “preventDefault()” which prevents it from making it an actual anchor event.

    Also, you can use event delegation here:

    $('#container").delegate("a[href=#]", "click", function(e){
    e.preventDefault();
    });

  • Adman

    $.each ist much fast as a native forLoop..

    var array = new Array ();
    for (var i=0; i<1000000; i++) { array[i] = 0; }

    console.time('native');
    var l = array.length;
    console.time('jquery');
    $.each (array, function (i) { array[i] = i; });
    console.timeEnd('jquery');

    for (var i=0;i<l; i++) { array[i] = i; }
    console.timeEnd('native');

    RESULT:
    jquery: 398ms
    native: 1142ms

    • Fred

      You have nested console.time() methods. If you change your code so there are two distinct timed sections, you’ll see (in FireFox 9 at least) that the native block runs about 50x faster

      var array = new Array();
      for (var i = 0; i < 1000000; i++) {
      array[i] = 0;
      }
      var l = array.length;

      console.time('jquery');
      $.each(array, function (i) {
      array[i] = i;
      });
      console.timeEnd('jquery');

      console.time('native');
      for (var i = 0; i < l; i++) {
      array[i] = i;
      }
      console.timeEnd('native');

      native: 8ms
      jquery: 385ms

      • Dar

        Excellent point.
        I was about to write it but than I saw your answer

  • Pappu Singh

    I have use ‘for’ instead of ‘$.each()’ and get execution of my script so fast.
    thanks.

  • http://komarnicki.webd.pl Paul Komarnicki

    OMG the “return false” advice is a horrible idea — you. should. never. do. that!

    • http://twitter.com/craigmdennis Craig Dennis

      event.preventDefault(); is all you need

    • http://matt-curtis.me/ Matt Curtis

      Care to give a little more detail? I personally always use event.preventDefault, but I’m not sure why return false is a bad idea.

  • http://www.paulund.co.uk Paul

    Great tips thanks.

    Didn’t know for loop was so much faster than each.

  • http://binhchontructuyen.com Bình Chọn

    Great post.
    attr(‘class’, …) faster than addClass(…) ??

    • http://www.jeffrey-way.com Jeffrey Way

      Each applies the class in different way. attr(‘class’…) will use setAttribute, and addClass() sets the classname of the element.

  • Brandon

    Wow, nice job. Greatest thing is that almost 3 years have gone by since this article was posted and it’s still valid. (I guess a few things may be different, but in general…)

  • http://www.e-sushi.net/ Mike Edward Moras (e-sushi™)

    Same article was posted in 2008 at hxxp://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip1

    I guess you don’t care to explain your *copyright violation*, or do you?

  • Ajay

    Thanks for this post.

    I want to know reason why there is execution difference between Client and Online using class selector eg. $(‘.item’)
    In both cases it will run(execute) on client side so why there is so much difference.

    • Nan Zhang

      suppose it will need to request data from servers sometimes online.

  • http://www.ghodmode.com/blog Vince Aggrippino

    The sample given for the use of selector context is incorrect. jQuery only accepts an element or a jQuery object as a context. This article used a string and that doesn’t work. Documentation: http://api.jquery.com/jQuery/?rdfrom=http%3A%2F%2Fdocs.jquery.com%2Fmw%2Findex.php%3Ftitle%3DCore%2FjQuery%26redirect%3Dno#jQuery-selector-context

    The following article, only available via the wayback machine, appears to be the source of most of this information: http://web.archive.org/web/20120303025708/http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx