JQuery speed: which one is faster, {ul # parent li} or {li.child}?

Just curious if there is an established “best practice” for target children within the parent.

For example, if I want to create a click event for children of a parent element, which one is preferable?

a) specify the parent element and id and do:

$('ul#parent li').click(function() {});

b) or, instead, give each of the children a class name and configure them directly:

$('li.child').click(function() {});

I ask, because I'm trying to squeeze every bit of performance, I can get a somewhat large application. The logic would determine that identifier targeting is faster than class name targeting, but the parent> child structure negates this advantage and justifies targeting with the class name instead?

Thank you for understanding.

+3
source share
4 answers

This will be the fastest option:

$('ul#parent li').click(function() {});

Always get down from the identifier selector, if possible.

However, if you have many elements <li>, it is cheaper to use .delegate(), for example:

$('#parent').delegate('li', 'click', function() { });

With .delegate()you attach an event handler one instead of n(number <li>), one for each <li>. It works by listening to what is clickbubbling up <ul>, if the startup time is killing you, this is a much better option. This is a run-time compromise linking many processors to the cost of the bubble (which is a very, very, very low cost). If you have many elements, this is almost always the best option.

+8

id , , , .

+1

. , , $ul_parent, ,

$ul_parent.children('li');

$('>li', $ul_parent); //same as above

. , , jQuery . jQ.

+1

Although theoretically $('ul#parent li')faster than $('li.child'), in principle, there are not many differences.

In the micro-object ( http://jsbin.com/uwela/4 ) there is 1 <ul id="parent">with 4096 <li class="child">, and 64 <ul>each with 64 <li>. In Firefox 3.6 on my machine all $('ul#parent li'), $('#parent li'), $('li.child'), $('.child')it takes about 210 milliseconds to attach onclick function.

But then the DOM on this test page is very shallow. Check it out on your page to make sure.

+1
source

Source: https://habr.com/ru/post/1751882/


All Articles