Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript event listener performance for hundreds of DOM elements

I have a <ul> that has many children (close to 3000 items) and some of the <li>s have many levels. I've attached an event listener on 'click' (I'm using jQuery) which I use to toggle the visibility of the children of an <li>.

I'm wondering how having so many event listeners impacts performance. (There are at the very least 1000!). Is this a big issue for performance?

I'm not really seeing much of an issue performance wise with newer web browsers, but IE8 seems to be very slow. Is it madly irresponsible to just whack an event listener on everything?!

like image 880
Richard Sweeney Avatar asked Jul 24 '13 18:07

Richard Sweeney


People also ask

Can I add an event listener to multiple elements in JavaScript?

To add the event listener to the multiple elements, first we need to access the multiple elements with the same class name or id using document. querySelectorAll() method then we need to loop through each element using the forEach() method and add an event listener to it.

What method can be used to listen for DOM events?

As a JavaScript programmer, you can utilize the DOM addEventListener() method for adding an event listener on any HTM object such as the window objects, HTML elements, HTML document or xmlHttpRequest object.

How many listeners can be attached to an event in Node JS?

The maximum number of event listeners that can be attached to the event can be set by the setMaxListeners function and the default value is 10.


1 Answers

The answer is a big whooping YES. Yes, it will affect performance. Event delegation was built for this exact thing. Instead of binding your handler to every single li, bind it to its parent, the ul. This way the ul will delegate the click event to li.

$("ul").on("click", "li", function () {
 //your code
});
like image 67
krishwader Avatar answered Nov 07 '22 22:11

krishwader