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
  • http://11heavens.com/ Caroline Schnapp

    Which is faster:

    Using context

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

    Or using descendant selector

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

    • http://swapnilsarwe.phpnet.us/ Swapnil Sarwe

      AS per my knowledge, 1st one should be faster, considering the fact, we are specifying the context and the expression as 2 different parameters.
      In 2nd case the complete string ’#class-container .class’ is an expression which jQuery then evaluates to find the class-container being an id and .class being an class inside the element with id ‘class-container’.

      Still would like to hear from the experts.

      • http://paulirish.com Paul Irish

        $(’#class-container .class’)
        would be faster. The most obvious reason is that browsers that have querySelectorAll can do that in one pass, vs selecting the context element and then selecting your target within it.

        Context should only be used when you already have a DOM reference. Typically:
        $(‘.class’,this)

        If you’re passing in a string or you’re doing something that looks like this:
        $(‘.class’,$(‘#container’))
        then you, my friend, are doing it wrong. :)

      • Yuriy

        I think faster would be this code:

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

        What you think?

      • http://emmett.be/thewebdev Emmett Pickerel

        I ran a test in FF3 in a small page (2.5k — I actually just used the Sizzle homepage). I put the ID “hd” on a UL and the class “myclass” on a child LI. These were my tests (5000 iterations):

        $(“.myclass”);
        $(“#hd .myclass”);
        $(“.myclass”, “#hd”);

        These were the results:
        .myclass: 1041ms
        #hd .myclass: 1697ms
        .myclass, #hd: 1176ms

        So, Swapnil is correct. BUT… what is surprising is that jquery’s className lookup is FASTER (every time) than getting it by context. I tried it again with a larger page (this one, actually, at 95k), and got slightly more expected results:

        .myclass: 1722
        #hd .myclass: 2382
        .myclass, #hd: 1169

        The middle one is still the slowest by a good margin. Seems as though starting your selector with an ID is a BIG no-no.

        I’d also suggest, instead of $(“#mydiv”), use $(document.getElementById(“mydiv”);. My speed tests showed the latter to be more than twice as fast in FF3:

        $(“#mydiv”): 189
        $( document.getElementById(“mydiv”) ): 72

    • http://james.padolsey.com James

      The actions involved with the first technique (with context):

      1 – Get element with an ID of “class-container” (the context)
      2 – Get ALL elements within that context
      3 – Filter out the ones that DON’T have a class of ‘class’

      And the second:

      1 – Get ALL elements on the page (this takes a while)
      2 – Filter out the ones that DON’T have a class of ‘class’
      3 – On each element, step up the DOM to check that an ancestor has an ID of “class-container” – remove those that don’t.

      .. Two very different approaches. In this situation, the first technique is quicker. Also, speed will vary across browsers… For example, browsers that support getElementsByClassName() will do better (the first two steps for the second technique can be merged in such browsers).

  • choise

    great !

  • http://twitter.com/SunnyLuthra Sunny

    Event delegation can improve jQuery performance too…

    Bad
    $(‘#myId’).click(function(){
    $(this).css(‘background’, ‘black’);
    });

    Good
    $(‘#myId’).click(function(e) {
    var clicked = $(e.target);
    clicked.css(‘background’, ‘black’);
    });

    • http://farinspace.com Dimas

      very true … helps with memory consumption as well as avoids reassigning events with dynamic elements …

  • http://webdevdotnet.blogspot.com Elijah Manor

    You should put your javascript at the bottom of the page

    http://developer.yahoo.com/performance/rules.html#js_bottom

  • http://twitter.com/timstl Tim Gieseking

    So, with #1, does anyone worry about the latest version of jQuery breaking whatever plugin they are using? It just seems like a risky move on a production site.

    • http://illuminatikarate.com/blog/ George Huger

      Absolutely, it WILL cause you trouble down the road. Including the latest version of jQuery is HORRIBLE advice, and should be removed from this post immediately.

      jQuery routinely changes fundamental aspects of the library between versions (such as deprecating the @ selector). If you’ve included the latest version of jQuery in a client’s live website I highly suggest you change to a specific version right away, and test thoroughly to make sure existing functionality is still working.

      We wrote a blog post on this recently, after upgrading from jQuery 1.2 -> jQuery 1.3 broke our website:

      http://illuminatikarate.com/blog/relative-offsets-are-handled-differently-between-versions-of-jquery/

      • http://farinspace.com Dimas

        I agree with you that you should not always be updating your production site to the latest version. You should basically do it only if you need a new feature or you need a bug fix, and even then it should be done with care.

        They way i took the first recommendation was that your projects should always START with the latest version.

    • http://www.peewee1002.co.uk peewee1002

      I do, the latest version doesn’ work with one of my lightboxes so i have to keep the old one,

      I do not make my owb plugins though and couldn’t get around it.

      i have started to put my scripts at the bottom though,

    • http://www.freshclickmedia.com Shane

      Yep, I’ve had countless issues with plugins and updating jQuery versions.

      For performance reasons, the latest version may be fastest, but you’re right when you say you need to be careful about plugins.

    • http://www.stevelove.org Steve Love

      You’re right, Tim. I’ve seen this break plugins on a site when they haven’t been updated against the latest version of jQuery. As George Huger reports in his comment, deprecated code in plugins is the biggest factor. The @ selector in particular causes the Thickbox plugin to break in jQuery 1.3.2. Fortunately it’s a simple fix in that case.

      Linking to Google’s jQuery source is a good idea. It’s like getting a free CDN. However, I would not follow the Editor’s note to automatically reference the latest version on a production site. You should instead specify a reference to the latest possible version that you’ve tested against. On the other hand, if you’re keeping up with the jQuery beta releases, this might not present an issue.

  • http://www.nick-brewer.com Nick

    Good stuff, as always!!

  • http://james.padolsey.com James

    In regard to #3 I’m a tad confused… Just did the test locally and the time difference is marginal if not non-existent. Also, how should “local” or “online” make any difference!?

    • http://twitter.com/SunnyLuthra Sunny

      “how should local or online make any difference!?”

      It will not make any difference, coz JS is a client side script..

      • http://james.padolsey.com James

        When why did the author include both on the graph…

      • http://giulio.hewle.com Giulio
        Author

        The two graphs are to show the delay you’d have because of conection; even if JS is client side, I think the code feels the effect of the issue.

        Also, I was a bit surpriesd too, when I noticed my two times (calculated with console.time) were different.

  • http://james.padolsey.com James

    Also, how does returning false increase performance?

    • http://twitter.com/SunnyLuthra Sunny

      em.. suppose your html is like as follows
      Click event

      $(‘#clickMe’).click (function () {
      // as if no “return false” your page will jump to top
      });

      • http://twitter.com/SunnyLuthra Sunny

        i meant to say that your functions don’t return false, you jump to the top of the page because of the hash#

        P.S how to write html in the comment ?

      • http://james.padolsey.com James

        Yes, and how does that improve performance? I’m being rhetorical.. – I’m just curious why the author put that in there.

      • Michael Thompson

        This is also wrong, if you’re using jQuery. Some browsers will not handle “return false” properly — sometimes it’ll bubble up the event stack, other times it’ll just be ignored.

        If you’re using jQuery you should be using “e.preventDefault();” instead of “return false”. Otherwise, you’re doing it wrong.

    • http://twitter.com/SunnyLuthra Sunny

      oh ya you are right, returning false has nothing to do with performance issues..

      • http://swapnilsarwe.phpnet.us/ Swapnil Sarwe

        Well I cant really say for 100% sure that my conclusion is right, still…

        As per functions in JS are concerned, they always return something, if nothing is specified, it returns undefined.
        Since After the function call JS interpreter always waits for the return value, its nice that it gets false which is a proper boolean value, rather than undefined which tells nothing about what is returned.
        And may be the interpreter shares a part of second analyzing undefined, which it wont spend when false is returned, b’coz it knows what false means.

      • http://giulio.hewle.com Giulio
        Author

        Yes, I included it for the reason Swapnil Sarwe mentioned

      • http://james.padolsey.com James

        @Swapnil; an interesting take on the issue but explicitly returning something WILL NOT improve performance… Plus, it’s just a strange tip… If a function needs to return something then let it otherwise there’s no benefit; JavaScript returns UNDEFINED by default.

        It’s like saying, always use single quotes instead of double quotes because they’re specified earlier in the charset… makes no sense.

    • JP
  • http://www.freshclickmedia.com Shane
    • ShipWreck

      Plug!
      That aside: they listed some other pretty useful tips.

      • http://www.freshclickmedia.com Shane

        I’m not affiliated to that website in any way. Therefore, it’s not a plug :)

    • http://11heavens.com/ Caroline Schnapp

      Thanks Shane, that’s a nice article.

  • Philip von Bargen

    Instead of using “return false;” at chapter 9 you could pass the event and use the “preventDefault()” function like this:

    $(‘#item’).click (function (e) {
    e.preventDefault();
    // stuff here
    });

    • http://giulio.hewle.com Giulio
      Author

      That’s another option, thanks for having pointed this out!

  • http://eduardosasso.com Eduardo Sasso

    Great tips. It’s always nice to improve performance even with jQuery which is already pretty fast.

  • http://adorama.com Adardesign

    Thanks,
    Great Post

  • Jan

    Any Mootools tutorials in the future?

    Thx

    • Brown Robott

      Mootools is a great js library but it doesn’t get the love that jQuery gets.

  • Jack F

    I prefer e.preventDefault() rather that return false; but that’s just a personal thing, inless you think there is any speed difference? Nice article.

  • http://jimneath.org Jim Neath

    So apart from some of these having nothing to do with performance, half of them aren’t about speeding up your “jQuery” as you’re just using native javascript instead of the jQuery functions.

    Another shoddy article, Nettuts.

    • http://giulio.hewle.com Giulio
      Author

      Thanks for the support, really.

      By the way, jQuery IS javascript and what most people don’t catch is it’s not always a great thing make indiscriminate use of jQuery built in methods; instead, try replacing them with some “pure” javascript

      • http://james.padolsey.com James

        Sarcasm isn’t needed… Jim makes a good point; most of your “tips” don’t really improve performance, plus some of them seem quite mis-informed; especially “avoid DOM manipulation” … God! You’re just going to be confusing so many beginners with this list. I didn’t show my concern originally but this really won’t do. Jeffrey, if you read this, I have to say I’m surprised you let this one through. Some of the points are valild but you know as well as I do, when a beginner sees one of these “10 top ways” lists they follow it without question. Misinformation is breaking the internet!

  • Henrik Hjelte

    Great tips, but remember what Knuth says: Premature optimization is the root of all evil. Don’t trade simplicity for optimization unless there is a measured need for optimization. Changing nice style (each) to ugliness (for) should not be done without a sound reason.

    • http://11heavens.com/ Caroline Schnapp

      I agree, Henrik. Even with much DOM manipulation, jQuery is still blazingly fast. 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. It’s that fast. I prefer code that is elegant and readable.

      • http://farinspace.com Dimas

        and on top of this, JS is run client side, so you do not have to make fine tuning code tweeks for millions of users, just for one!

    • http://buup.mephir.com Giulio
      Author

      Hm, never thought of this, but good point

  • AnonymousCoward

    Some good advice, some not so good….

    1. Use the latest version, but only after you’ve thoroughly tested it. Linking to a resource that changes outside of your control is a recipe for disaster.

    2, 8. JavaScript performance in general, not jQuery

    3, 4, 6. How did you do your profiling here? Script would be running client side in all cases…

    9. True sometimes, but needs an explanation of when/why.

    Biggest problem with this post is that there’s already been umpteen on the exact same topic by other blogs in the past month, which means that this brings absolutely nothing new to the table, and is borderline plagiarism (that is, in the parts that weren’t misinformation…). I’m about one bad post away from unsubscribing from NetTuts. It’s turning into an echo chamber of slightly modified posts that other bloggers actually spent time on…

  • http://myfacefriends.com Myfacefriends

    thanks for this wonderful tuts!

  • http://labs.dariux.com Dario Gutierrez

    Really useful dude.

  • http://www.dsaportfolio.com.br Diego SA

    WOw! That’s what I call by “ultimate jQuery tips tutorial”. So well explained and these graphics make everything become easier for have notion of how jQuery operates. Some awesome tips could save my day! Thanks a lot!

  • http://icosidodecahedron.com Michael Kozakewich

    CSS selectors go from right to left. In other words, #id .class would search for all .class, and then look to see which of those are also descendants of #id. Do you know if jQuery does the same thing? If so, $(“.class”,”#id”) would be a lot faster than $(“#id .class”).

    As for returning false: I was looking at a Wikipedia article about CMSes, and I realized their long lists were sortable. I could sort by name or version, but when I tried to sort by ‘last date updated’, which had blank or missing cells, it just bumped me all the way to the top of the screen, and I had to scroll past several tables to get back where I was.
    Considering it took me upwards of 5000ms to scroll back down, it really does make it faster to specify a return code.

  • http://www.twitter.com/ravenflx Josh

    Top #1 way to instantly increase your mootools performance

    1. Switch to jQuery.

    Just kidding only poking fun :)

  • http://gomobile.com.ar/ Zim

    Excellent, I appreciate it! Thank you

  • http://www.yakuru.com Lloyd Vincent

    Beautiful collection of tips, there’s something for everyone here from beginner to advanced.

    I just started learning jQuery so this came at the perfect time for me, before I’ve developed any bad habits.

  • http://blog.designsector.org Sunil Agarwal

    Wow I didn’t realize there’s such a big difference between for() and each(). Great post. Thanks a lot!

  • http://blog.insicdesigns.com insic

    9. Return False

    The explanation is confusing, maybe there are other valid reasons why we should put return false other than it is annoying. :)

    • http://www.awmcreative.com Aaron

      I think the whole point of #9 is to keep the page from scrolling all the way to the top when an action is called. Other than an explanation of being annoying it’s a better user experience to keep this from happening, which is why return false is used.

      • Kanedogg

        Well thats true, i use return false in any j/script for that exact reason!
        E.G: If your posting a form and returning your result via “ajax” or alike having save the user the PAIN of doing a whole page refresh !!

        Or another good one is the Link Or href use – as was mentioned, save a link click jumping you to the top of a page use it there like so – onclick=”doSomething(‘blahblah”); return false;”

        another one for these is void(0); Hope dis helps some?
        cheers

  • http://tuvidaloca.net Rata

    For WordPress I use a plugin with great success: „Use Google Libraries“, just have a look, works fine.

    Nice tut :)
    Thanks.

    Kind regards
    Rata

  • http://thinkadrian.com Adrian von Gegerfelt

    Would be nice to include graphs for Safari 4, Firefox 3, FF3.5 and IE8…

  • http://mankzblog.wordpress.com Mats

    1: Who would point their production site to an unknown version of a library? Noone!!

    2. Has nothing to do with JQuery

    Point 3, 4, 5 & 6 are worth reading.

    Point 7-10 …?

    The online vs local comparison, WTF??

  • http://www.wibben.de/ Björn

    Yet another resource for performance tips:
    http://www.artzstudio.com/2009/04/jquery-performance-rules/

    Best regards,
    Björn

    • Andrea

      Thanks Björn!

  • przemeko

    I really don’t understand separating “local” and “online”? What’s the diffrent?

  • http://www.freelancer-id.com Alaa Al-Hussein

    I didn’t know about these 10 things before.

    Thanks for providing such important information.

  • http://mohamedaslam.com Mohamed Aslam

    Nice tutorial. Expeting these kind of tutorials for Prototype – script.aculo.us and Mootools.

    Anyway nice job!

  • wayno007

    Very useful tut.

  • http://www.nicoleandgreg.net Greg Givan

    Rather than being concerned with “return false” for click events, I’ve begun setting the href attribute value to

    javascript:void(0);

    which does not cause the page to ‘jump’

    • http://james.padolsey.com James

      Greg! Don’t do this!

      For one, you shouldn’t be using the ‘javascript’ pseudo protocol and you definitely should not be using inline JavaScript! Search “unobtrusive JavaScript” … you’ll be enlightened :)

  • http://bitsamppixels.com Fredrik W

    I prefer using:

    $(‘#el’).click(function(event){
    event.preventDefault();
    /* … */
    })

    because it’s less magical.

  • http://www.jaaulde.com/ Jim

    I like to store references to the jQuery object which was returned by the factory if I will need to operate on the same matched collection again later.

    var $myContainer = $( ‘#container’ ).show();

    Later when I need to operate on the element which matched, I can chain off of $myContainer instead of having the factory find the element again.

    This is also how I handled context before reading the tip on the context parameter (which I had no idea about, so THANK YOU for pointing it out). If I built a widget of some sort, I put it all into some kind of container element with an ID. I then get a reference to the collection that matches that ID (as I did in the above code example) and get items from within it by chaining .find() or .children() off of the reference.

    Now that I know about the context parameter, I’ll be using it OR my previous method depending on which makes more sense at a given time.

    Thanks for a good article.
    Jim

  • http://www.freshclickmedia.com Shane

    I’m all for software performance, and we should all keep these things in mind.

    However, to best determine differences between browsers and coding methods, loops with many iterations are used. Whilst I understand this highlites those differences, does it really present a ‘real-world’ situation? Does the ‘typical’ usage of javascript involve such intensive processing? Perhaps I’m wrong here (and I feel like I’m inviting a shed-load of comments), but performance isn’t as important as, say, a realtime C++ system – is it? :)

  • http://brandonaaron.net/ Brandon Aaron

    In regards to #5, the the optional context argument is actually used a little differently. Passing a selector as the context gets turned into this instead:

    $(‘#class-container’).find(‘.class’);

    Hopefully this blog post will help clear things up in regards to the context: http://brandonaaron.net/blog/2009/06/24/understanding-the-context-in-jquery

    • http://11heavens.com/ Caroline Schnapp

      Thank you, Brandon!

  • http://hayespotter.com Hayes Potter

    You should have included what return: false; actually means/does. It tells jQuery to end the query and to not do anything else, nothing whatsoever.

    • http://james.padolsey.com James

      What? “end the query” …. I think you mean “end the function”. Returning false has absolutely nothing to do with jQuery – it’s a JavaScript statement.

  • http://eventsavvi.com A’braham Barakhyahu

    For #7, would rebuilding the fragment each time you add something be faster than a perpend? That would be surprising if it is.

  • Prashant

    How you guyz made http://nettuts.s3.amazonaws.com/359_jqueryTips/jquery.png this image, I want to make something like this, please tell me how to do this, is there any software or tool for this ??

  • Johan

    How does using multiple $(document).ready areas affect performance?

  • http://www.downwithdesign.com Gareth Hardy

    Another useful article! Thanks nettuts! :)

  • http://www.twitter.com/seansumido Sean Sumido

    Guys, question… It is really important to add XTHML doc, when using AJAX?

    because I still us the HTML 4.0

    and i still use tables instead of CSS

  • Jeremy Dill

    Abstraction will always cost you some performance, but I really think jQuery team needs to do some more performance testing and ask themselves why some basic functions such as .each take so much more time that native js which requires only a tad bit more code to write. Maybe they can find some performance gains somewhere while maintaining the excellent abstraction.

    For example, something that has really be bothering me…

    regarding
    1. var list = ”;
    2.
    3. for (var i=0; i<1000; i++) {
    4. list += ”+i+”;
    5. }
    6.
    7. (‘#list’).html (list);

    I find it is actually faster to avoid .html(), and instead perform native js function of innerHTML on the object. For example:

    $(‘#list’)[0].innerHTML(list);

    While this kind of tweak really only matters when looping, it comes up a lot when I am coding, and I hate having the temptation to break away from normal jQuery in order to achieve performance.

  • http://www.anthonyjamesbruno.com Anthony James Bruno

    Here is a version of the YUI Compressor online: http://yui.2clics.net/

  • http://www.somihanquoc.com somihanquoc.com

    Hay phet, cha hieu gi. Ong Tay nao dich duoc ta viet gi thi moi goi la gioi :D

    • Noguchi

      Kiddy, go away

  • http://www.code-pal.com Sumeet Chawla

    Awesome tips.. thanks a ton :)

  • http://blog.dynatrace.com Andrea Grabner

    Here is some more insight to the CSS Selector Performance: http://blog.dynatrace.com/2009/11/09/101-on-jquery-selector-performance/