Tip: Improve scroll listener performance

JavaScript, Browser, Event · Mar 7, 2023

When working with scroll listeners in JavaScript, one can often run into performance issues. This is because scroll listeners are triggered on every single scroll event, which can be quite frequent. Most of the time, such listeners are used for infinite scrolling and lazy loading, meaning that the scroll event won't be intercepted. As such, Event.preventDefault() will not be called, guving us an optimization opportunity.

window.addEventListener('scroll', () => {
  // Do something
  // Can't use `preventDefault` here
}, { passive: true });

As demonstrated in this code snippet, setting the passive option to true will enable certain performance optimizations in the browser. This way, the browser will know that it can safely skip the event queue and execute the scroll listener immediately. The result is a much smoother experience for the user, as the scroll event will be handled immediately, instead of being queued and handled later.

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • JavaScript Event Handling

    Event handling needs to be done right in JavaScript. Pick up some tips and tricks to create a better user experience.

    Collection · 15 snippets

  • Add multiple listeners

    Adds multiple event listeners with the same handler to an element.

    JavaScript, Browser · Oct 22, 2020

  • Add event listener to element

    Adds an event listener to an element with the ability to use event delegation.

    JavaScript, Browser · Oct 21, 2020

  • Add event listener to all targets

    Attaches an event listener to all the provided targets.

    JavaScript, Browser · Apr 22, 2021