jQuery selector optimization

后端 未结 2 1932
迷失自我
迷失自我 2020-12-13 10:31

Be specific on the right-hand side of your selector, and less specific on the left.

// unoptimized
$(\'div.data .gonzalez\');

/         


        
2条回答
  •  眼角桃花
    2020-12-13 10:51

    The book sort of mentions this in passing, but I'm fairly certain that advice is specific to Sizzle (the jQuery selector engine), not generally. Your mileage may vary, but a browser that implements querySelectorAll is unlikely to show a real-world difference.

    Sizzle works inside-out when appropriate, and so may look for td.gonzales and then look to see if it's within a .data, rather than the other way around. I remember when Sizzle first came out, this was a bit of a surprise, but it actually worked out better. So you can see why the more specific the right-hand side of the descendant selector, the better.

    Here's a test case, try that in IE7 and you'll see a marked preference for the more specific right-hand side. But try it in a modern browser and you should seem basically no difference.

    This is all micro-optimization, though, and pretty much useless in the absence of a real-world problem to solve, because it varies dramatically based on the elements on your page. Useful to remember if you actually have a slow selector causing you trouble on older browsers, perhaps, but other than that...

提交回复
热议问题