You have used infinite scroll a thousand times — on social media, on shopping sites, on search results. New content appears as you scroll down, and there is no "next page" button in sight. Under the hood it is one observer and one flag.
What you are building
A feed that loads 10 more items every time you scroll near the bottom, using a fake data source so you can see the pattern clearly.
The JavaScript: IntersectionObserver watches the bottom
const feed = document.querySelector('#feed');
const sentinel = document.querySelector('#sentinel');
let page = 0;
let loading = false;
async function loadMore() {
if (loading) return;
loading = true;
const items = await fakeFetch(page); // your API call goes here
items.forEach((item) => {
const div = document.createElement('div');
div.textContent = item.title;
feed.appendChild(div);
});
page++;
loading = false;
}
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) loadMore();
});
observer.observe(sentinel);
The sentinel is an empty element at the bottom of the feed. When it scrolls into view, the observer fires and you load more. No scroll event listeners, no math on scroll positions.
The fake data source
function fakeFetch(page) {
return new Promise((resolve) => {
setTimeout(() => {
const items = Array.from({ length: 10 }, (_, i) => ({
title: 'Post ' + (page * 10 + i + 1)
}));
resolve(items);
}, 500);
});
}
Swap this for a real fetch() call to your API and the rest of the code stays exactly the same. That is the point of the pattern: the loading logic does not care where the data comes from.
Stop when there is nothing left
async function loadMore() {
if (loading) return;
loading = true;
const items = await fakeFetch(page);
if (items.length === 0) {
observer.disconnect();
document.querySelector('#end-message').textContent = 'You are all caught up.';
return;
}
// ... append items ...
}
Forgetting this is how feeds end up firing requests forever. When the API returns an empty page, disconnect the observer and show a message.
The one thing to remember
The loading flag is not optional. Without it, a fast scroller can trigger five requests at once, and your feed ends up with duplicated items in a random order. One boolean prevents all of it.
Top comments (0)