Lazy Loading Background Images
You'll learn how to defer CSS background images until they're actually needed, using JavaScript to add classes only when elements scroll into view.
Unlike <img> tags (which support native loading="lazy"), CSS background images defined in your stylesheet load immediately, even if they're far off-screen. This wastes bandwidth and slows initial page load, especially when you have hero sections, decorative panels, or card components with background images that users might never see.
The solution is class-based lazy loading: start with a placeholder class (or no background), then use the Intersection Observer API to detect when the element enters the viewport and dynamically add a CSS class that applies the background image.
How It Works
- Define two CSS classes: one without the background image (initial state) and one with it (loaded state)
- Apply the initial class to elements in your HTML
- Observe elements with Intersection Observer
- Add the loaded class when the element becomes visible
.hero-section {
/* Initial state - no background */
min-height: 400px;
background-color: #f0f0f0;
}
.hero-section.bg-loaded {
background-image: url('hero-bg.jpg');
background-size: cover;
}
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('bg-loaded');
observer.unobserve(entry.target);
}
});
});
document.querySelectorAll('.hero-section').forEach(el => {
observer.observe(el);
});
Think of it like a stage curtain: the scenery (background image) stays hidden backstage until the spotlight (viewport) reaches that part of the show.
Key Takeaway: Lazy load CSS background images by keeping them out of your initial stylesheet and adding image-containing classes with JavaScript only when elements scroll into view, dramatically reducing unnecessary downloads.