HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Improve JavaScript scroll listener performance

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
improvejavascriptscrollperformancelistener

Problem

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, giving us an optimization opportunity.
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.

Solution

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

Code Snippets

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

Context

From 30-seconds-of-code: passive-scroll-listener-performance

Revisions (0)

No revisions yet.