Abstract
A brief summary of the article
jQuery is a fantastic Javascript library but it also has the tendency to make it a little bit too easy to write inefficient code.
Content
Main article body
Let’s get this out of the way first; I love jQuery, it makes DOM manipulation straightforward and has just the right level of involvement for a Javascript framework. Basically if you’re doing nothing particularly fancy, you need nothing more than the jQuery Core and you could reasonably find yourself using most parts of the core functionality without being guilty of going a bit too crazy with Javascript functionality.
The jQuery selectors are fast, and they seem to keep getting faster. It’s got to the point where using a jQuery selector is only marginally slower than using the native DOM functions.
The problem is with chaining. As one of jQuery’s most praised features chaining is a mixed blessing, you can do a lot of powerful things in just one line using it but chances are you’ve solved the problem in a way that’s far from efficient. Each time you add another link to the chain you are effectively adding another loop that must be iterated over; in just a few short steps you will probably have added a lot of algorithmic complexity and unnecessary repetition to your code.
There are a few tricks you can use to optimise your code (this applies to any coding, but I’ve found jQuery makes it a little bit too easy to be lazy):
- Cache repeated selections, if there’s a selector that you always find yourself using, save the result to a variable – this means the actual selection only gets run once.
- If you know the actual DOM functions and they’re safe to use in all browsers you should probably use them, they’ll be faster. This is especially important if the function is inside a loop.
- In general it’s good to minimize your result set as soon as possible so that you are working on less data, but in jQuery this might mean that you are running an extra chained function when you don’t really need to. Say you are doing .filter(“span”).each(fn), you can combine this into a single .filter(fn), and just modify your inner function to ignore span element.
- Don’t forget other coding tricks. There are thousands of ways to improve algorithms and eliminate unnecessary loops but it’s easy to forget about them when enjoying the simplicity and elegance that jQuery provides. You may end up with code that’s a bit more verbose (okay, often it will be a lot more verbose) but users that are on machines slower than the ones you test on will thank you.
Feel free to contribute any other tricks you’ve come across that improve the performance of jQuery-based algorithms
Comments
What people have had to say about this article
-
Thanks for that, I wouldn’t have thought of the complexity that chaining adds. I’m definitely going to be more careful with how I write my jQuery code from now on.
Add Comment
Use this form to add your own comments

Montoya #
03:44pm, 10th November 2007