How to Speed up jQuery: Selector Tip

November 27, 2011

I ran into a slow jQuery selector in older browsers on a large document and learned a cool tip: jQuery selectors should get more specific from left to right. Selectors are parsed in reverse order, so making sure that your most specific selector is on the right will increase performance.

The example below shows how not to write a jQuery selector using this technique:

$('p#intro b').each(function() {
   //Do something
});

In the above example, jQuery finds all elements of type ‘b’ and then looks to see if the have a parent of p#intro.

Instead, it is recommended that you use the find function to speed up your jQuery. This took my 30,000 element document parsing time from 15 seconds to about 2:

$('p#intro').find('b').each(function() {
   //Do something faster
});

This example does the opposite, finding a elements matching p#intro and looking in their children using the find() function to find all elements of type ‘b’.

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive