Implementing Custom Image Lazy Loading
You'll learn how to build your own JavaScript-based image lazy loader using the Intersection Observer API for browsers that don't support native lazy loading.
The Core Idea
While loading="lazy" is convenient, you may need a custom solution for older browsers, more control over thresholds, or to add loading animations. You'll use the Intersection Observer API (which you've already learned) to detect when images enter the viewport, then swap a placeholder source with the real image URL.
How It Works
Think of it like a security guard watching doorways: the Intersection Observer "watches" where images are relative to the viewport. When an image crosses into view (or gets close), you trigger the actual image load.
Basic Implementation Pattern
// Store real image URL in data attribute
// <img data-src="real-image.jpg" src="placeholder.jpg" alt="...">
const images = document.querySelectorAll('img[data-src]');
const imageObserver = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
// Swap placeholder with real image
img.src = img.dataset.src;
img.removeAttribute('data-src');
// Stop observing this image
observer.unobserve(img);
}
});
});
// Start observing each image
images.forEach(img => imageObserver.observe(img));
The pattern is simple: use a data-src attribute to hold the real URL, start with a lightweight placeholder in src, observe all images, and when they intersect the viewport, swap data-src into src. Once loaded, stop observing that image to free up resources.
Key Takeaway: Custom lazy loading with Intersection Observer gives you full control over when and how images load, providing a fallback for browsers without native support while allowing for enhanced loading experiences like animations or progressive image loading.