Skip to content

Commit 78fd9d4

Browse files
committed
optimize-selectors qSA before Sizzle
1 parent 851b0b9 commit 78fd9d4

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

page/performance/optimize-selectors.md

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,28 @@
77

88
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.
99

10-
## ID-Based Selectors
10+
## Save calls to `querySelectorAll`
1111

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" );
1316
17+
// Against only 1 call with this:
18+
$( ".container div .robotarm" );
1419
```
15-
// Fast:
16-
$( "#container div.robotarm" );
1720

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+
2025
```
26+
// A long selection with nonstandard pseudo-classes inside:
27+
$( "#global.ready .part .list li a:contains('qwerty'):first" );
2128
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+
```
2332

2433
## Specificity
2534

@@ -51,9 +60,6 @@ A "flatter" DOM also helps improve selector performance, as the selector engine
5160
Selections that specify or imply that a match could be found anywhere can be very slow.
5261

5362
```
54-
$( ".buttons > *" ); // Extremely expensive.
55-
$( ".buttons" ).children(); // Much better.
56-
5763
$( ".category :radio" ); // Implied universal selection.
5864
$( ".category *:radio" ); // Same thing, explicit now.
5965
$( ".category input:radio" ); // Much better.

0 commit comments

Comments
 (0)