IntersectionObserver
You'll learn how to efficiently detect when elements enter or leave the viewport using the IntersectionObserver API.
What Is IntersectionObserver?
The IntersectionObserver API watches elements and notifies you when they intersect with the viewport (or another ancestor element). Think of it like having a security camera at your door—it alerts you when someone enters or leaves your property, but doesn't constantly monitor the street.
Before this API, developers had to use scroll event listeners and manually calculate element positions, which was slow and inefficient. IntersectionObserver does this work asynchronously and much more efficiently.
Basic Usage
Create an observer by providing a callback function that runs when intersection changes occur:
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
console.log('Element entered viewport!');
// Lazy load an image, start animation, etc.
}
});
});
// Start watching an element
const element = document.querySelector('.lazy-image');
observer.observe(element);
Common Use Cases
Lazy loading images: Only load images when they're about to appear on screen, saving bandwidth and improving page load time.
Infinite scroll: Load more content as the user scrolls near the bottom.
Animation triggers: Start animations when elements become visible.
Options
You can configure when the callback fires:
const observer = new IntersectionObserver(callback, {
threshold: 0.5, // Fire when 50% visible
rootMargin: '100px' // Fire 100px before entering viewport
});
Key Takeaway: IntersectionObserver efficiently monitors when elements enter or leave the viewport, making it perfect for lazy loading, infinite scroll, and viewport-triggered animations without the performance cost of scroll event listeners.