JavaScript
Public
Infinite Scroll with IntersectionObserver
Load the next page when a sentinel approaches the viewport and prevent duplicate requests.
#javascript
#intersection-observer
#infinite-scroll
#performance
JavaScript
const sentinel = document.querySelector('[data-load-more]');
let page = 1;
let isLoading = false;
let hasMore = true;
const observer = new IntersectionObserver(
async (entries) => {
const entry = entries[0];
if (!entry.isIntersecting || isLoading || !hasMore) {
return;
}
isLoading = true;
try {
const response = await fetch(`/api/items?page=${page + 1}`);
const result = await response.json();
appendItems(result.items);
page += 1;
hasMore = result.hasMore;
} finally {
isLoading = false;
if (!hasMore) {
observer.disconnect();
}
}
},
{
rootMargin: '300px 0px',
},
);
if (sentinel) {
observer.observe(sentinel);
}