Lazy Loading Images with JavaScript Fallback
You'll learn how to create a resilient lazy loading strategy that works across all browsers, combining native and custom solutions.
Understanding the Hybrid Approach
While loading="lazy" provides effortless lazy loading in modern browsers, older browsers like Internet Explorer and older Safari versions don't support it. A robust solution detects native support and falls back to JavaScript-based lazy loading when needed.
Think of it like a smart thermostat: if the house has modern climate control, use that; if not, rely on a manual backup system. Both achieve the same goal—comfort—just through different mechanisms.
The Core Pattern
First, check if the browser supports native lazy loading by testing the loading property on an HTMLImageElement. If it exists, the browser will handle everything. If not, initialize an Intersection Observer to manage loading manually.
Detection logic:
const supportsNativeLazyLoad = 'loading' in HTMLImageElement.prototype;
if (supportsNativeLazyLoad) {
// Browser handles it natively
console.log('Native lazy loading supported');
} else {
// Fall back to Intersection Observer
const images = document.querySelectorAll('img[loading="lazy"]');
const imageObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
imageObserver.unobserve(img);
}
});
});
images.forEach(img => imageObserver.observe(img));
}
Your HTML remains clean and progressive:
<img src="placeholder.jpg" data-src="real-image.jpg" loading="lazy" alt="Description">
Modern browsers load lazily via the loading attribute. Older browsers ignore it and rely on your JavaScript to swap data-src into src when the image approaches the viewport.
Key Takeaway: A hybrid lazy loading approach provides native performance for modern browsers while ensuring graceful degradation for older ones using Intersection Observer, maximizing both compatibility and efficiency.