Intersection Observer for Custom Lazy Loading
You'll learn how to build a flexible lazy loading system that triggers when elements become visible, going beyond simple loading="lazy".
The Core Idea
While the native loading="lazy" attribute works well for basic image lazy loading, the Intersection Observer API gives you fine-grained control over when and how resources load as elements enter the viewport. This is perfect for custom lazy loading scenarios: background images, videos, complex components, or images that need special handling.
How It Works
Think of Intersection Observer as a watchful guard at the edge of your viewport. You tell it which elements to watch, and it alerts you the moment they cross a threshold (like entering the visible area). No more scroll event listeners clogging your main thread!
Here's the basic pattern:
// Create the observer
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
const src = img.dataset.src;
img.src = src; // Load the image
observer.unobserve(img); // Stop watching once loaded
}
});
});
// Watch images with data-src attributes
document.querySelectorAll('img[data-src]').forEach(img => {
observer.observe(img);
});
Your HTML would look like:
<img data-src="photo.jpg" alt="Lazy loaded image">
The observer fires when the image enters the viewport, swapping data-src into src to trigger the actual download. Once loaded, we stop observing that element to free resources.
This approach gives you flexibility—adjust thresholds, handle multiple element types, add loading classes, or integrate with your framework's lifecycle.
Key Takeaway: Intersection Observer enables custom lazy loading with precise control over when elements load, superior performance compared to scroll listeners, and flexibility beyond native loading="lazy".