Lazy Loading with Root Margin
You'll learn how to start loading images before they become visible, creating a seamless experience without awkward empty spaces.
The Problem with Default Lazy Loading
When you lazy load images using the Intersection Observer API, they typically load the moment they enter the viewport. But this creates a small delay — users might see a blank space or placeholder flash before the image appears. It's like waiting for an elevator to arrive after you press the button instead of having it already on its way.
What is Root Margin?
The rootMargin option in Intersection Observer works like CSS margins — it extends or shrinks the viewport boundary used for intersection calculations. By setting a positive rootMargin, you create an invisible buffer zone around the viewport that triggers loading early.
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
}, {
rootMargin: '200px' // Load 200px before entering viewport
});
document.querySelectorAll('img[data-src]').forEach(img => {
observer.observe(img);
});
How It Works
With rootMargin: '200px', images start loading when they're 200 pixels before reaching the visible viewport. By the time the user scrolls to where the image should appear, it's already loaded (or mostly loaded). The experience feels instant.
You can specify different values for each side: rootMargin: '50px 0px 200px 0px' (top, right, bottom, left).
Key Takeaway: Use rootMargin in Intersection Observer to preload images just before they enter the viewport, eliminating loading delays and creating smoother scrolling experiences.