I have quite a few jquery / javascript listeners on my web page and I will reduce them as much as I can. However, for the listeners that remain, there are scenarios where I make them display:none
at certain points. Here are my questions:
1) What is best practice regarding listeners, should I add or remove listeners as I show / hide elements?
2) Which is best performance wise?
3) If I end up having lots of listeners, is it best to apply an on listener event to the whole body, or is it best to apply listeners to only things that need listening to?
Since we only need the listener for our modal, it should be removed whenever the user cannot interact with our modal any longer. The same is true for any element that can be toggled as well as animations on elements.
Always cleanup your event listeners. Do this with window. removeEventListener when your component unmounts. By cleaning up, you'll avoid listening to events multiple times and memory leaks.
According to the jquery Documentation when using remove() method over an element, all event listeners are removed from memory. This affects the element it selft and all child nodes. If you want to keep the event listners in memory you should use . detach() instead.
Go to the objects tab, view the Document object (don't click on edit) and scroll down to Event Handlers. Select the one to delete and press delete.
A general rule of thumb is as follows:
Remove events on teardown.
Since you are not removing the DOM element, the listener should persist, performance wise there is no drawback unless you have hundreds of thousands of listeners.
The time it takes to micromanage hidden elements listeners aren't enough to outweigh any perceived performance gains.
You can also use event delegation (bubbling) for when you have a large number of children that require listening to by listening on the parent:
$('div').on('click', function (e) {
// check e.target for specific child node you require listening on
})
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