Improved jQuery selector performance tips

It's important to make sure your optimise your jQuery selectors to improve performance. This is especially important on sites that make heavy use of jQuery.

1) Select with Efficiency:

$('#id') – the fastest method 
$('tag.classname') – next fastest: this grabs all matching tags FIRST, then iterates through them to find the matching classes 
$('.classname') – the slowest: it has to iterate through ALL DOM ELEMENTS on the page

2) Cache to Avoid Reselection 

Interacting with the DOM as little as possible will drastically speed up your applications.

Instead of making isolated selections such as this: 

$('#sidebar .promo').hide(); 
$('#sidebar .newPromo').show(); 
$('#sidebar').after(somethingcool); 

You can cache the sidebar selection, removing the need to return to the DOM each time: 

var sb = $('#sidebar'); 
sb.find('.promo').hide(); 
sb.find('.newPromo').show(); 
sb.after(somethingcool); 

When working with large DOM manipulation and interaction, caching different modules, sections of the page, or elements can really speed things up. 

3) Don't Clutter the Global Namespace 

When possible, keep the global namespace clean by using anonymous functions.
Since so much jQuerying doesn't need to store variables, you can put them into an anonymous function

(function($){ 
//all your jQuery and variables go here and auto-run, and don't get remembered. 
//if you do need to store a variable, simply declare it globally before your function closes: 
Window.myStoredVar = 'Stored info'; 
})(jQuery); 
Alert(myStoredVar) // 'Stored info'
Justin Chevallier

Justin Chevallier

Avid Drupal site builder & user for +9 years.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.