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.
问题:
回答1:
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.
回答2:
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.
回答3:
One thing these articles don't address is what your starting point is. If you are starting with the entire DOM tree, then these articles are actually useful.
However, if you have an element to start with, it then depends on what your search is. Most of my dynamic javascript with MVC templates tends to grab the element on which the action is taken, then do a search for parent objects. This eliminates the need to uniquely name a container when they are randomly generated-- makes things a lot easier from a dynamic devlopment standpoint.
While searching for a near-parent node may not be as fast as searching for an ID, the performance should be negligible compared to the amount of time and/or performance of generating and tracking a number of unique IDs.
As with everything in development, "it depends" will reign here.
回答4:
I notice a lot of these type of questions are restricted to performance comparison between different jQuery selectors. I recently came across an article that compares jQuery selectors against their native Javascript counterparts.
It might sound like a lot of hassle, but the performance gain is quite substantial. More than I imagined actually.
Article: http://www.sitepoint.com/jquery-vs-raw-javascript-1-dom-forms/