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?!
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.
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.
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.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With