jQuery Performance Tips Cheat Sheet

I was hunting for jQuery performance tricks for a while to tune my heavy dynamic web app. After digging in a lot of articles decided to make a list of the best common performance tips. I also built a handy jQuery Performance Cheat Sheet that can be printed or placed on my desktop.

Selectors performance tips:

1. Always Descend From an #id

This is the golden rule of the jQuery selectors. The fastest way to select an element in jQuery is by ID:

$('#content').hide();

or select multiple elements descending from an ID:

$('#content p').hide();

2. Use Tags Before Classes

The second fastest selector in jQuery is the Tag selector ($(‘head’)) because it maps to a native JavaScript method, getElementsByTagName(). The best way is to prefix a class with a tag name (and descend from an ID):

var receiveNewsletter = $('#nslForm input.on');

The class selector is among the slowest selectors in jQuery; in IE it loops through the entire DOM. Avoid using it whenever possible. Never prefix an ID with a tag name. For example, this is slow because it will loop through all <div> elements looking for the ‘content’ ID:

var content = $('div#content'); // VERY SLOW, AVOID THIS

Also, DON’T descend from multiple IDs:

var traffic_light = $('#content #traffic_light'); // VERY SLOW, AVOID THIS

3. Use Sub-queries

Cache the parent object then run queries on it:

var header = $('#header');

var menu = header.find('.menu');

// or

var menu = $('.menu', header);

See live example →

4. Optimize selectors for Sizzle’s ‘right to left’ model

As of version 1.3, jQuery has been using the Sizzle Javascript Selector Library which works a bit differently from the selector engine used in the past. Namely it uses a ‘right to left’ model rather than a ‘left to right’. Make sure that your right-most selector is really specific and any selectors on the left are more broad:

Page 1 of 5 | Next page