Back to Snippets

Infinite Scroll Loader JS

A feed of update cards that loads more as you scroll. When the bottom of the list comes into view a spinner shows, the next batch arrives, and the spinner steps aside for the new cards. After the last page the feed says so and stops asking.

There is no scroll listener. An IntersectionObserver watches a sentinel element after the list and fires when it enters the viewport, which is exactly the moment to fetch. A rootMargin on the observer starts the fetch a little early so the new cards are usually there before the visitor reaches the gap. A loading flag stops a second request while one is in flight, and once the final page has rendered the observer is disconnected.

The fetch is simulated with a timeout that builds ten cards per page. Replace the body of loadPage with a real request that returns a page of items and the rest of the script stays the same.

0
#javascript
#css
#infinite scroll
#intersection observer
#feed
#list
#loading
#ui