snippetjavascriptModeratepending
IntersectionObserver — lazy loading and infinite scroll
Viewed 0 times
IntersectionObserverlazy loadinfinite scrollviewportvisibility
browser
Problem
Need to detect when elements enter/leave the viewport for lazy loading images, infinite scroll, or scroll-triggered animations. Scroll event listeners are expensive and cause jank.
Solution
Use IntersectionObserver API for performant visibility detection. The browser handles the intersection math off the main thread.
Code Snippets
Lazy loading and infinite scroll with IntersectionObserver
// Lazy load images
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
},
{ rootMargin: '200px' } // Start loading 200px before visible
);
document.querySelectorAll('img[data-src]').forEach((img) => {
observer.observe(img);
});
// Infinite scroll
const sentinel = document.getElementById('sentinel');
const scrollObserver = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) loadNextPage();
});
scrollObserver.observe(sentinel);Revisions (0)
No revisions yet.