How to implement infinite scroll with Intersection Observer
· Category: JavaScript
Short answer
Use the IntersectionObserver API to watch a sentinel element at the bottom of your list. When the sentinel enters the viewport, fetch and append more items. This approach is far more performant than listening to scroll events.
Details
Create an observer with new IntersectionObserver(callback, options) and call .observe(sentinel) on a dummy element placed after your list. In the callback, check entry.isIntersecting to trigger the next data load. Once data is fetched, append it to the DOM and optionally unobserve until the load completes to prevent duplicate requests.
Infinite scroll pairs naturally with debouncing or throttling companion logic. For a refresher on controlling high-frequency events, see How to debounce and throttle event handlers in JavaScript. If you are fetching data asynchronously, how to use async/await will help you keep the code readable.
Tips
- Provide an accessible loading announcement with an
aria-liveregion so screen reader users know when new content arrives. - Always offer an alternative pagination UI for users who prefer explicit navigation.
- For related performance techniques, read about what is the JavaScript event loop and how does it work to understand how observer callbacks are scheduled.