Attaching JavaScript Handlers to Scroll Events = BAD!

It’s a very, very, bad idea to attach JavaScript handlers to the window scroll event. Instead, use this technique Twitter uses.

Check out John Resig’s most excellent article, Learning from Twitter for an in-depth explanation why is is a bad idea and why the alternative below works better.

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!