Event listener performance antipatterns
Event listener performance antipatterns change over time. For example, when Internet Explorer support was broadly required due to its market share, adding event listeners to DOM nodes and subsequently deleting the nodes would not clean up the event listeners, causing memory leaks. This doesn’t occur anymore in modern browsers.
An event listener antipattern that is often caught by the Lighthouse page performance auditing tool is scroll
event listeners that aren’t set to be passive. Passive event listeners are more performant because event.preventDefault()
doesn’t intercept and stop the event’s default behavior. This allows browsers to set the event listener to be non-blocking since the listener can’t act on the event.
Making an event listener passive simply involves passing { passive: true }
as the third parameter to addEventListener()
:
document.addEventListener(
'scroll',
...