|
7 | 7 |
|
8 | 8 | Selector optimization is less important than it used to be, as more browsers implement `document.querySelectorAll()` and the burden of selection shifts from jQuery to the browser. However, there are still some tips to keep in mind.
|
9 | 9 |
|
10 |
| -## ID-Based Selectors |
| 10 | +## Save calls to `querySelectorAll` |
11 | 11 |
|
12 |
| -Beginning your selector with an ID is always best. |
| 12 | +``` |
| 13 | +// If in your HTML there are 2 .container with 5 div in each, |
| 14 | +// this line will call querySelectorAll 13 times (1 + 2 + 2*5). |
| 15 | +$( ".container" ).children( "div" ).find( ".robotarm" ); |
13 | 16 |
|
| 17 | +// Against only 1 call with this: |
| 18 | +$( ".container div .robotarm" ); |
14 | 19 | ```
|
15 |
| -// Fast: |
16 |
| -$( "#container div.robotarm" ); |
17 | 20 |
|
18 |
| -// Super-fast: |
19 |
| -$( "#container" ).find( "div.robotarm" ); |
| 21 | +## Try to segregate the nonstandard parts of your selection |
| 22 | + |
| 23 | +When you select elements, jQuery will call `querySelectorAll` with your selection. If `querySelectorAll` throws an error, jQuery will refer to its Sizzle engine. So, if you are using at least one of these nonstandard pseudo-classes: `:contains()`, `:has`, `:even`, `:submit`, etc. You will not take advantage of the native `querySelectorAll`. |
| 24 | + |
20 | 25 | ```
|
| 26 | +// A long selection with nonstandard pseudo-classes inside: |
| 27 | +$( "#global.ready .part .list li a:contains('qwerty'):first" ); |
21 | 28 |
|
22 |
| -The `.find()` approach is faster because the first selection is handled without going through the Sizzle selector engine – ID-only selections are handled using `document.getElementById()`, which is extremely fast because it is native to the browser. |
| 29 | +// A long standard selection with a filter outside (faster): |
| 30 | +$( "#global.ready .part .list li a").filter( ":contains('qwerty'):first" ); |
| 31 | +``` |
23 | 32 |
|
24 | 33 | ## Specificity
|
25 | 34 |
|
@@ -51,9 +60,6 @@ A "flatter" DOM also helps improve selector performance, as the selector engine
|
51 | 60 | Selections that specify or imply that a match could be found anywhere can be very slow.
|
52 | 61 |
|
53 | 62 | ```
|
54 |
| -$( ".buttons > *" ); // Extremely expensive. |
55 |
| -$( ".buttons" ).children(); // Much better. |
56 |
| -
|
57 | 63 | $( ".category :radio" ); // Implied universal selection.
|
58 | 64 | $( ".category *:radio" ); // Same thing, explicit now.
|
59 | 65 | $( ".category input:radio" ); // Much better.
|
|
0 commit comments