Infinite Scroll
November 8, 2021
I always thought an infinite scroll would be tricky to create, but the Intersection Observer API provided in modern JavaScript makes it a piece of cake.
The IntersectionObserver constructor is passed a callback and an (optional) options object. This creates a bounding box that can target a number of elements, and pass data about those targets into the callback function. By default, this bounding box is the viewport.
Within the callback, each target can be checked for intersection with the observer, with code executed conditionally. In my codepen, I placed the target after the content list, and on intersection, a ‘page’ variable is incremented to increase how many elements are rendered, which also pushes the target back out of the bounding box.
For comparison, try commenting out line 31, which will force the page to load all elements immediately. You’ll be looking at a blank page for much longer while waiting for all of the elements to be added to the DOM.