Intersection Observer for Lazy Loading
Intersection Observer for Lazy Loading
Section titled “Intersection Observer for Lazy Loading”Introduction
Section titled “Introduction”IntersectionObserver provides fine-grained control over when resources load by detecting when elements enter the viewport.
Basic Observer Setup
Section titled “Basic Observer Setup”const observer = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.isIntersecting) { const el = entry.target; loadResource(el); observer.unobserve(el); // Stop observing once loaded } });}, { rootMargin: '200px', // Start loading 200px before visible threshold: 0.1 // Trigger when 10% visible});Lazy Loading Any Element
Section titled “Lazy Loading Any Element”function lazyLoad(element) { const observer = new IntersectionObserver(([entry]) => { if (entry.isIntersecting) { // Trigger loading element.classList.add('visible'); element.src = element.dataset.src; observer.disconnect(); } }, { rootMargin: '100px' });
observer.observe(element);}
// Usagedocument.querySelectorAll('[data-lazy]').forEach(lazyLoad);Infinite Scroll
Section titled “Infinite Scroll”const sentinel = document.querySelector('#scroll-sentinel');
const observer = new IntersectionObserver(async ([entry]) => { if (entry.isIntersecting) { const items = await fetchMoreItems(); appendItems(items); }}, { rootMargin: '400px' });
observer.observe(sentinel);Performance Tips
Section titled “Performance Tips”- Use
rootMarginto start loading before the element is visible - Call
unobserve()ordisconnect()after loading to stop observing - Set appropriate
thresholdvalues — 0 is often best - Avoid observing hundreds of elements simultaneously
Summary
Section titled “Summary”IntersectionObserverprovides custom control over lazy loading- Use
rootMarginto preload before visibility - Always unobserve/disconnect after loading
- Great for infinite scroll, image loading, and ad loading