Question

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

$('#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

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

Was it helpful?

Solution

Adding it to each element one at a time vs adding it to 50 at once makes no difference after the event is bound. 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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top