Skip to content

Instantly share code, notes, and snippets.

@NikitaPokryshko
Created September 28, 2018 15:46
Show Gist options
  • Save NikitaPokryshko/0be03524395b6df6dd4681dbe0b316fd to your computer and use it in GitHub Desktop.
Save NikitaPokryshko/0be03524395b6df6dd4681dbe0b316fd to your computer and use it in GitHub Desktop.
Best practices about scrolling pages' events

Best Practices

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

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. Instead 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).

Always cache the selector queries that you’re re-using.

It’s not clear why Twitter decided to re-query the DOM every single time the scroll event fired, but this does not appear to be necessary (since scrolling itself didn’t change the DOM). They could’ve saved the result of that single query to a variable and looked it up whenever they wanted to re-use. This would’ve resulted in absolutely no querying overhead (which is even better than having the faster getElementsByClassName code!).

conclusion

Thus, combining these two techniques, the resulting code would look something like:

var outerPane = $details.find(.details-pane-outer”),
didScroll = false;

$(window).scroll(function() {
didScroll = true;
});

setInterval(function() {
if ( didScroll ) {
didScroll = false;
// Check your page position and then
// Load in more results
}
}, 250);

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment