Intersection Observer API Basics
What you'll learn: How to use the Intersection Observer API to detect when elements become visible in the viewport, enabling custom lazy loading solutions.
What Is the Intersection Observer API?
The Intersection Observer API is a browser tool that watches elements and tells you when they enter or leave the viewport (or another specified area). Think of it like a motion sensor at a store entrance—it automatically detects when someone (an element) crosses the threshold without you having to constantly check.
This is much more efficient than the old method of listening to scroll events and manually calculating positions, which can hurt performance.
How It Works
You create an observer, tell it what to watch, and provide a callback function that runs when visibility changes:
// Create the observer
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
console.log('Element is now visible!');
// Load image, start animation, etc.
}
});
});
// Start watching an element
const image = document.querySelector('img[data-src]');
observer.observe(image);
The entries parameter contains information about each observed element. The isIntersecting property tells you whether the element is currently visible.
Why This Matters for Lazy Loading
Instead of relying on loading="lazy", you can build custom lazy loading that triggers exactly when you want—maybe when the image is 200px away from the viewport, or only after a user stops scrolling.
Key Takeaway: The Intersection Observer API efficiently detects when elements enter the viewport, giving you precise control over lazy loading without performance-draining scroll listeners.