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(); 

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

var sb = $('#sidebar'); 

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

//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'; 
Alert(myStoredVar) // 'Stored info'
Justin Chevallier

Justin Chevallier

Avid Drupal site builder & user for +10 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.