Photo by DALL·E (AI-generated illustration)
Website speed isn’t just a technical detail — it’s a major factor in user experience and SEO performance. A slow-loading page can make visitors leave before they even see your content.
Most developers already know how to lazy load regular images using the loading="lazy" attribute.
But here’s the catch: CSS background images don’t support native lazy loading.
Unlike <img> tags, background images load as soon as your CSS is parsed — even if they’re not visible yet. So, how do you make them load only when needed?
Let’s explore how to add lazy loading to background images using CSS and JavaScript.
Step-by-Step: Add Lazy Loading for Background Images
Here’s a simple and effective way to implement lazy loading using the Intersection Observer API.
HTML
<div class="lazy-bg" data-bg="image.jpg"></div>
CSS
.lazy-bg {
min-height: 400px;
background-size: cover;
background-position: center;
}
.loaded {
background-image: var(--bg-image);
}
JavaScript
document.addEventListener("DOMContentLoaded", () => {
const lazyBackgrounds = document.querySelectorAll(".lazy-bg");
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const div = entry.target;
const bg = div.dataset.bg;
div.style.setProperty('--bg-image', `url(${bg})`);
div.classList.add('loaded');
observer.unobserve(div);
}
});
});
lazyBackgrounds.forEach(bg => observer.observe(bg));
});
Explanation
The data-bg attribute stores the image URL.
When the section becomes visible, JavaScript sets the --bg-image variable with that URL.
CSS then applies it as a background image.
Once loaded, the observer stops tracking that section.
Result? Your background images will only load when the user scrolls to them — saving bandwidth and speeding up your site.