Wickey312
Wickey312

Reputation: 576

Event Listener Remove or Keep - Best Practice

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?

Upvotes: 6

Views: 3841

Answers (2)

Guru Evi
Guru Evi

Reputation: 184

1/2) What is best practice regarding listeners, should I add or remove listeners as I show / hide elements? --> Adding/removing events is slow. You can probably benchmark it but the best recommendation is to keep them and let the garbage collection handle it in case you delete objects. It saves you code and is probably more readable, plus garbage collection (cleanup) should ideally happen (depending on implementation and a host of other things) when the user is not waiting/interacting.

2) Which is best performance wise? --> See 1. Benchmark it if you're unsure.

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? --> How much. Is your code readable either way? If you end up listening to the entire body, your code will be handling a LOT more events (mouse over every single object, clicks, keyboard inputs etc.) and typically you'll want to then filter out only relevant events and dispatch them to the function. This makes your code very messy (lots of if/then) and will eventually end up costing you way more in performance than what you thought to save. The best thing is to only handle events on the objects that are relevant to your process. Way simpler, way easier, way faster.

Upvotes: 1

Nijikokun
Nijikokun

Reputation: 1524

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.


  1. Remove listeners when you remove elements (teardown).
  2. Listen to a generic class applied to multiple elements instead of individual elements, use data attributes to identify them if required.
  3. Listen to things that need to be listened to.

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
})

Upvotes: 8

Related Questions