Lazy Loading Background Images
What you'll learn: How to lazy load CSS background-image properties using classes and the Intersection Observer API.
The Challenge with Background Images
While native lazy loading (loading="lazy") works great for <img> elements, it doesn't apply to CSS background images. Since backgrounds are set via stylesheets, the browser loads them immediately when the CSS rule applies—even if the element isn't visible yet. This wastes bandwidth and slows initial page load.
The Class-Swapping Technique
The solution is to delay applying the background image until the element scrolls into view. You do this by:
- Start with a placeholder class on your element (no background set yet)
- Use Intersection Observer to detect when it enters the viewport
- Add a new class that contains the
background-imageCSS rule
Think of it like keeping a photo in an envelope (no background) until someone actually looks at your desk (viewport), then you take it out and display it (add the class with the background).
How It Works
You define two CSS classes:
.hero-section {
/* Other styles, no background yet */
}
.hero-section.loaded {
background-image: url('large-hero.jpg');
}
Then use Intersection Observer to detect visibility and swap classes:
const hero = document.querySelector('.hero-section');
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('loaded');
observer.unobserve(entry.target);
}
});
});
observer.observe(hero);
When the element intersects the viewport, you add the loaded class, triggering the browser to fetch and display the background image.
Key Takeaway: Lazy load background images by using Intersection Observer to add a CSS class containing the background-image property only when the element becomes visible, saving bandwidth on images users might never see.