Lazy Loading Background Images
You'll learn how to defer loading CSS background images until they're actually needed by dynamically applying classes when elements scroll into view.
The Challenge with Background Images
While HTML <img> tags support native lazy loading with loading="lazy", CSS background-image properties load immediately when the stylesheet is parsed—even if the element is far off-screen. This wastes bandwidth and slows initial page load.
The Dynamic Class Solution
The trick is to conditionally apply CSS classes that contain the background-image property. Here's how it works:
- Start with empty backgrounds: Don't set
background-imagein your default CSS - Create a loaded state class: Define a class (like
.bg-loaded) that includes the background image - Use Intersection Observer: Watch when the element enters the viewport
- Apply the class: Add
.bg-loadedto trigger the background image download
Implementation Pattern
/* No background initially */
.hero-banner {
min-height: 400px;
background-color: #f0f0f0;
}
/* Background loads only when class is added */
.hero-banner.bg-loaded {
background-image: url('hero.jpg');
background-size: cover;
}
const bgElements = document.querySelectorAll('.hero-banner');
const bgObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('bg-loaded');
bgObserver.unobserve(entry.target);
}
});
});
bgElements.forEach(el => bgObserver.observe(el));
The browser only downloads the background image when the class is added—effectively lazy loading it!
Key Takeaway: Lazy load CSS background images by keeping them out of initial styles and dynamically adding a class with background-image when Intersection Observer detects visibility.