Attaching JavaScript Handlers to Scroll Events — a how-NOT-to, use this instead.

Don’t do what I’ve seen countless devs do — attach JavaScript handlers to the window scroll event. There’s a better way, here’s Twitter’s solution.

I came across an article by John Resig, Learning from Twitter — it completely changed how I attach JavaScript handlers to scroll events. It’s a simple trick that will help boost performance and help keep your code object-orientated.

It’s a very, very, bad idea to attach handlers to the window scroll event.

The Wrong Way

Depending upon the browser the scroll event can fire a lot and putting code in the scroll callback will slow down any attempts to scroll the page (not a good idea). Any performance degradation in the scroll handler(s) as a result will only compound the performance of scrolling overall.

$( window ).scroll( function() {
  // Do your thang!

The Correct Way

It’s much better to use some form of a timer to check every X milliseconds OR to attach a scroll event and only run your code after a delay (or even after a given number of executions – and then a delay).

var scrolling = false;

$( window ).scroll( function() {
  scrolling = true;

setInterval( function() {
  if ( scrolling ) {
    scrolling = false;
    // Do your thang!
}, 250 );

Hope this helps to clear things up and provides some good advice for future infinitely-scrolling-page developers!

Author: Ben Marshall

Red Bull Addict, Self-Proclaimed Grill Master, Entrepreneur, Workaholic, Front End Engineer, SEO/SM Strategist, Web Developer, Blogger

2 thoughts on “Attaching JavaScript Handlers to Scroll Events — a how-NOT-to, use this instead.”

  1. For input events (touchstart, wheel, scroll etc) most modern browsers support ‘passive’ events e.g.

    document.addEventListener(‘wheel’, (evt) => {
    // … do stuff with evt
    }, { capture: false, passive: true})

    This allows the UI thread to immediately handle the scroll event before passing over control to your custom event handler. Without passive option, your custom handler will always be called before the UI thread does anything with the event.

    Scroll event throttling (adding a delay between handling the events) can be implemented quite neatly using lodash or rxjs, if you have them in your build already

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.