views:

61

answers:

2

Looking at improving the performance of my jquery selectors. so any tips or articles as the best per formant jquery selectors? For example selecting the a div's id. Anywhere online I can provide html and compare the different selectors I can use to select the required element.

+6  A: 

You can compare selector performance here: http://jsperf.com/

Just setup your HTML, include jQuery and place each selector you want to compare as a test case.

Many of the rules here still apply, however the game changed a bit in jQuery 1.4.3+, after that Sizzle (jQuery's selector engine) will use querySelectorAll() in browsers that support it.

Nick Craver
Note that Sizzle has used `querySelectorAll()` for quite a while. It was always used for `document` contexts (ie `nodeType == 9`). 1.4.3 introduced using it on element nodes (ie `nodeType == 1`) as well.
Crescent Fresh
A: 

This article goes into some detail about jQuery selectors and their performance. It's mainly about using jQuery the right way. Since a lot of jQuery use revolves around selectors, the article spends some time on them.

Basically a few things to remember:

  • If you're looking for performance, use selectors that delegate to native DOM-inspection methods (getElementById, getElementsByTagName)
  • Cache results
  • Pseudo-selectors can cause a performance hit.
Vivin Paliath