1. Use an ID if Possible
HTML ID attributes are unique in every page and even older browsers can locate a single element very quickly:
|
|
2. Avoid Selecting by Class Only
The following class selector will run quickly in modern browsers:
Unfortunately, in older browser such as IE6/7 and Firefox 2, jQuery must examine every element on the page to determine whether “myclass” has been applied.
The selector will be more efficient if we qualify it with a tag name, e.g.
|
|
jQuery can now restrict the search to DIV elements only.
3. Keep it Simple!
Avoid overly complex selectors. Unless you have an incredibly complex HTML document, it’s rare you’ll need any more than two or three qualifiers.
Consider the following complex selector:
|
|
p#intro must be unique so the selector can be simplified:
|
|
4. Increase Specificity from Left to Right
A little knowledge of jQuery’s selector engine is useful. It works from the last selector first so, in older browsers, a query such as:
|
|
loads every em element into an array. It then works up the parents of each node and rejects those where p#intro cannot be found. The query will be particularly inefficient if you have hundreds of em
tags on the page.
Depending on your document, the query can be optimized by retrieving the best-qualified selector first. It can then be used as a starting point for child selectors, e.g.
|
|
5. Avoid Selector Repetition
It’s rarely necessary to use the same selector twice. The following code selects every p
tag three times:
|
|
Remember jQuery offers chaining; multiple methods can be applied to the same collection. Therefore, the same code can be re-written so it applies to a single selector:
|
|
You should cache the jQuery object in a variable if you need to use the same set of elements multiple times, e.g.
|
|
Unlike standard DOM collections, jQuery collections aren’t live and the object is not updated when paragraph tags are added or removed from the document. You can code around this restriction by creating a DOM collection and passing it to the jQuery function when it’s required, e.g.
|
|