3 Simple Things to Make Your jQuery Code Awesome

jQuery is one of the most popular (if not the most) JavaScript libraries in existence and a great number of people use it to do some amazing things. Personally, jQuery is what got me excited for learning JavaScript. The problem is that a lot of programmers don’t understand that with all that power massive amounts of CPU cycles are used. As much as jQuery engineers try to optimize jQuery, they are always limited in how fast they can make it go. There are a few things that you, as a user of jQuery, can do to make your jQuery code faster.

1 - jQuery Object Caching

Caching your jQuery objects may possibly be the best thing you can do to cut your code down to run leaner and meaner. If you use the same selector more than once in your code, or if you query the DOM inside a loop or in a function that is run more than once, then you can probably benefit a lot from caching your queries inside a variable. Consider the following 3 examples:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Loop
for (var i=0; i<100; i++) {
$('ul.special').append('<li>'+i+'</li>');
}

// Multiple Functions that each have the
// chance to be called mulple times
$('#showbutton').on('click', function() {
$('#box').show();
});
$('#hidebutton').on('click', function() {
$('#box').hide();
});

// Just re-querying
$('p').width(150);
$('p').css('color', 'red');
$('p').addClass('awesome');

In all of these cases, you could save some DOM searching trips by assigning the jQuery object to a variable (generally prefixed with a dollar sign to distinguish it as a jQuery object), like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var $ul = $('ul.special');
for (var i=0; i<100; i++) {
$ul.append('<li>'+i+'</li>');
}

var $box = $('#box');
$('#showbutton').on('click', function() {
$box.show();
});
$('#hidebutton').on('click', function() {
$box.hide();
});

$('p').width(150).css('color', 'red').addClass('awesome');

One of the most expensive operations you can do is query the DOM, especially in older browsers that can’t be optimized for with built-in functions. Each time you query the DOM (with a few exceptions), you have to search through the entire DOM to find each and every matching element, which can take time, especially on large documents. The third example actually uses chaining, which is similar to caching because you still optimize down to one DOM search, but it doesn’t require you to save the jQuery object to a variable.

2 – Selector Optimization

The CSS selectors used in your DOM queries can sometimes make more of a difference in performance than the lack of caching the results of that search. The first thing you have to realize is that the selectors are read from right to left, so you always want your most specific selectors (most notably id’s) to be as far to the right as possible. Many times, though, you are trying to find the children of an element with an id, therefore you can’t have the id selector furthest to the right in the full selector. There is a way around this though, via context or using find or children:

1
2
3
4
5
6
7
// Instead of this:
$('#id p');

// Try one of these:
$('p', '#id');
$('#id').find('p');
$('#id').children('p')

The following selectors are ranked from fastest to slowest. Always try to have a faster selector further to the right or within the context parameter/find/children to make your selections as fast as possible.

  1. $('#id');
    An id selector is easily the fastest selector. There are two reasons for this: 1) There is only ever one element with an id, so once it is found, the searching stops and 2) browsers have a built in function for searching for elements by their id (document.getElementById()), and built-in functions run much quicker than hand-made functions.
  2. $('tag');
    Searching by a tag name is somewhat fast only because all browsers support the built-in function called document.getElementsByTagName().
  3. $('.class');
    Searching via class would probably be comparable to searching by the tag name, but you have to be careful just because IE8 and below don’t support the native document.getElementsByClassName().
  4. $('[attribute]'); or $('[attribute=value]'); or $(':pseudo');
    No browser currently has a native function available to JavaScript for searching with these selectors, so jQuery is required to crawl through the DOM by itself and check each element to see if it matches this selector. There are some modern browsers that have document.querySelectorAll(), which is a native function that can take any selector, but even with the increased performance from this function, the look-ups for these selectors is still quite slow.

3 – Delegating Events

The third and final optimization involves events. If you are attaching an event handler to each and every cell of a table, you could be using a lot more memory than you really need to, plus it takes a little time to apply a handler to each of those cells. This might be done something like this:

1
2
3
$('table td').on('click', function() {
// Do Something
});

Event delegation allows us to attach a single event handler to a parent element – saving us memory and set up time – that only fires when the event is triggered on specific child elements. So, using the example above, we could attach a single handler to the table that would fire any time someone clicked on a td, but not when someone clicks on a th or other element within the table. The code to do this looks like this:

1
2
3
$('table').on('click', 'td', function() {
// Do Something
});

Notice that the selector for the elements that you actually want the event to trigger on is now the second argument to the on function. The cool thing is that this still refers to the td that was clicked and not to the table, just like it would if you had attached the handler directly to the cells. This also has the added benefit that if more table cells are dynamically added in, you don’t need to add the event handler to them because they are already covered by the parent element.

Concluding the Optimizations

So there’s 3 ways to be a more awesome jQuery programmer. I know this topic has been discussed countless times around the internet, but you never know when you’ll run into someone who hasn’t heard of these. Besides, it never hurts to be reminded. So, remember to cache, use fast selectors, and delegate your events to earn the respect of jQuery programming pros everywhere. Also remember to comment and/or share. Happy Coding!

Author: Joe Zimmerman

Author: Joe Zimmerman Joe Zimmerman has been doing web development ever since he found an HTML book on his dad's shelf when he was 12. Since then, JavaScript has grown in popularity and he has become passionate about it. He also loves to teach others though his blog and other popular blogs. When he's not writing code, he's spending time with his wife and children and leading them in God's Word.