Handling Lazy Load Failures and Fallbacks
You'll learn how to gracefully handle scenarios where lazy-loaded resources fail to load and provide fallback strategies.
Why Lazy Loading Can Fail
Lazy loading relies on network requests that can fail for various reasons: poor connectivity, server errors, browser extensions blocking requests, or missing resources. Without proper error handling, users see broken images or missing content—a poor experience that defeats the purpose of optimization.
Implementing Error Handling
When using the Intersection Observer API (as you learned in earlier lessons), wrap your lazy loading logic in try-catch blocks and listen for error events:
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
const src = img.dataset.src;
img.addEventListener('error', () => {
// Fallback: show placeholder or retry
img.src = '/images/placeholder.jpg';
img.classList.add('load-failed');
});
img.src = src;
observer.unobserve(img);
}
});
});
Retry Logic
For critical images, implement retry attempts with exponential backoff:
function loadImageWithRetry(img, src, retries = 3) {
img.src = src;
img.addEventListener('error', function handleError() {
if (retries > 0) {
setTimeout(() => {
loadImageWithRetry(img, src, retries - 1);
}, 1000 * (4 - retries)); // 1s, 2s, 3s delays
} else {
img.src = '/images/fallback.jpg';
}
img.removeEventListener('error', handleError);
});
}
Think of it like a delivery service: if the first attempt fails, they try again later, and if it still doesn't work, they leave a "sorry we missed you" note (your fallback image).
Key Takeaway: Always implement error handlers and fallback strategies for lazy-loaded resources to ensure users never see broken content, even when networks fail.