开发者

Speed difference between very similar jQuery expressions in IE

In IE, compare the speed of execution of an expression along the lines of

$('div.gallery div.product a");

to the very similar

$('div.gallery').find("div.product").find("a");

Sometimes the second variant runs faster, sometimes slow开发者_C百科er. Often the speed difference is a factor of 2 or more. What is going on?


The first variant will do the following:

  1. Find all anchor tags in the page
  2. Only leave the ones with ancestor div.product
  3. Only leave the ones with ancestor div.gallery

The second one

  1. Find elements with class .gallery and tag div
  2. Search for div.product in their descendants
  3. Search for anchor tags in their descendants

So the first one will search for elements from right to left, while the second one will search them from left to right.

Which is faster depends on your site structure but the first one is the recommended way, because browsers match CSS selector the same way.

If you want to increase speed make sure that the rightmost selector is as specific as possible.

e.g.: in this case you can add a special class for your anchor tags like .gallery-link and then your query will become a simple a.gallery-link which in IE will invoke a getElementsByTagName function for the anchor tags then they will be filtered by their class name. Notice that because you don't have to traverel up the DOM tree your query becomes significantly faster. The cost is a bit more complex markup. For costly queries it may worth it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜