简体   繁体   English

Javascript(jQuery)事件监听器性能

[英]Javascript (jQuery) Event Listener Performance

I wonder if many Event Listeners take on perfomance. 我想知道是否有许多事件监听器都具有出色的性能。

for example if i have 50 Elements that listen on click events, does it make a change if i have 50 Event Listeners for each element one listener like so 例如,如果我有50个元素监听单击事件,那么如果我每个元素有50个事件监听器,一个监听器,它是否会做出更改?

$('#one').on("click",function(){ // do something; });
$('#two').on("click",function(){ // do something else; });
...
$('#fifty').on("click",function(){ // do something else; });

or just one event listener 或仅一个事件侦听器

$('.listen_to_click').on("click",function(){ 
// handle action here depending on data attribute or something else 
});

//or does jQuery add here an event listener internally on every .listen_to_click element so that it doesn´t make any change at all -  in this case does it change when you do like so

$('body').on("click",'.listen_to_click',function(){
 // handle action here depending on data attribute or something else
 });

or when you use plain javascript do something like this 或当您使用普通javascript时,请执行以下操作

document.getElementByTagName('body').addEventListener("click",function(e){
// handle action on e.target or something else
});

instead of 代替

document.getElementById('one').addEventListener("click",function(e){
    // do something
    });
document.getElementById('two').addEventListener("click",function(e){
    // do something else
    });
...
document.getElementById('fifty').addEventListener("click",function(e){
    // do something else
    });

so what i want to know is.. does it make any sense in performance 所以我想知道的是..它在性能上是否有意义

Thanks 谢谢

Adding it to each element one at a time vs adding it to 50 at once makes no difference after the event is bound. 将事件一次绑定到每个元素一次与一次添加到50个元素没有区别。 You may be able to do a jsperf to prove that doing one or the other binds the events faster, but the actual handling of the events will not be any different assuming that in both cases you are binding directly to the elements and not doing delegation. 您也许可以做一个jsperf来证明做一个或另一个可以更快地绑定事件,但是假设在两种情况下您都直接绑定到元素而不进行委派,则事件的实际处理不会有任何不同。

On the other hand, using event delegation such as binding a click event on the body and testing if the event.target matches a selector will be slower than binding the click event directly to the element because the event will have to bubble up to the body before it can be handled. 另一方面,使用事件委托(例如在主体上绑定click事件并测试event.target是否与选择器匹配)比将click事件直接绑定到元素要慢,因为事件必须冒泡到主体上才可以处理。 It will also have to execute all handlers that happen before it, so that can impact the performance too. 它还必须执行所有在此之前发生的处理程序,这样也会影响性能。 That's why when using event delegation it's best to set the delegate target as close to the event target as possible. 这就是为什么在使用事件委托时,最好将委托目标设置为尽可能接近事件目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM