Skip to content

Instantly share code, notes, and snippets.

@simonwoo
Last active November 28, 2016 16:11
Show Gist options
  • Save simonwoo/c37f84c70f35df3290f2c70d6a9e9806 to your computer and use it in GitHub Desktop.
Save simonwoo/c37f84c70f35df3290f2c70d6a9e9806 to your computer and use it in GitHub Desktop.

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