ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)
Set your Publisher ID in src/config/ads.ts to display live ads.
How-To: 50+ Real-World Developer Recipes• 6 min read
How To: Infinite Scroll with IntersectionObserver
Implement smooth, high-performance infinite scrolling using the native IntersectionObserver API without scroll lag.
Why IntersectionObserver Beats onScroll Handlers
Attaching listeners to window.onscroll forces continuous calculations on the main thread, causing frame drops. The IntersectionObserver API offloads position detection directly to the browser compositor.
Sentinel-Based Infinite Loader
const sentinel = document.getElementById('scroll-sentinel');
let page = 1;
let isLoading = false;
const observer = new IntersectionObserver(async (entries) => {
const entry = entries[0];
if (entry.isIntersecting && !isLoading) {
isLoading = true;
page++;
await loadMoreItems(page);
isLoading = false;
}
}, { rootMargin: '200px' }); // Load 200px before user reaches the bottom
observer.observe(sentinel);ADVERTISEMENT
Google AdSense Slot (inContentBanner)
Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
Which property in IntersectionObserver options loads content slightly before the user reaches the sentinel element?