Optimize your Selectors for speedSelector Speed
- Other weird ones
It could be that some of the other selectors can be faster than class. I haven't done extensive research, so if you're in doubt try it out.
While it's okay in your css to have verbose selectors that describe the structure more accutely e.g.
#page #header #nav .current, doing this can really slow down jQuery selector speed. Remember that you don't have to worry about the cascade affect in jQuery, just be concise. The Sizzle Selector Engine of jQuery 1.3 also processes selectors in a right to left fashion, so in the example above it's going to get all elements and check each one for a class matching "current" and then compare the parents of what it finds to the rest of the selector removing anything that doesn't match the pattern. This selector can be made much faster like this
#nav li.current. By adding the
li jQuery switches from getting all elements to using the DOM getElementsByTagName(), which is much faster, then it just looks up and sees the parent with #nav and stops. A lot less filtering will take place.
If you're making the same selections repeatedly in your scripts you should just set a variable.
Can be written as
$("#aside").hide(); ... $("#aside").show();
var $aside = $("#aside").hide(); ... $aside.show()
Evaluate re-selecting as opposed to traversalSometimes it can be a lot faster to go
So if you're in a situation where it looks like a reselect can be faster try it out and compare. The difference between these can vary a lot so I can't generalize here, but test it in your situation. Don't forget that code readability matters so if the difference is trivial make the code easier to understand.
Rely on jQuery less