Frontend System Design · Lesson 47 of 86 · 4 min
Lazy Loading Images and Videos
This is a fundamental web performance pattern. You need to explain the trade-offs between native and JS-based approaches and how to prevent layout shift.
Lazy loading defers loading off-screen media until the user scrolls near it. This improves initial page load metrics like First Contentful Paint (FCP) and Largest Contentful Paint (LCP) by reducing the number of critical-path requests. It also saves bandwidth for users who don't scroll through the entire page.
You have two primary methods to implement this.
Choose Your Weapon: loading="lazy" vs. Intersection Observer
The first decision is whether to use the browser-native attribute or a JavaScript-based API.
Use loading="lazy" when you can. It's a simple attribute on <img> and <iframe> tags. The browser handles all the logic. It's declarative, requires zero JavaScript, and is the most performant option.
<img src="image.jpg" loading="lazy" width="800" height="600" alt="...">
The browser determines the optimal distance from the viewport to start loading, which is a complex and evolving heuristic. You have no direct control over this distance.
Use IntersectionObserver for more control or for non-standard cases. This JavaScript API lets you trigger a callback when an element enters the viewport. You need it for lazy-loading CSS background images, videos with custom controls, or for supporting older browsers (with a polyfill). It also gives you precise control over when the load is triggered via the rootMargin option.
In an interview, state that you'd start with
loading="lazy"for its simplicity and performance. Then, introduceIntersectionObserveras the more powerful tool for custom requirements or for assets that don't support the native attribute. This shows you prefer simple solutions but know the advanced ones.
Implementing with IntersectionObserver
The pattern is to store the media URL in a data-* attribute and only move it to the src attribute when the element is visible.
First, the HTML. The src can point to a tiny placeholder, like a 1x1 transparent pixel, or be omitted entirely.
<img class="lazy" data-src="full-image.webp" width="800" height="600" alt="...">
Then, the JavaScript. Create one observer to watch all lazy-load elements.
const lazyElements = document.querySelectorAll<HTMLImageElement>('.lazy');
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
// Is the element in the viewport?
if (entry.isIntersecting) {
const element = entry.target as HTMLImageElement;
// Swap data-src for src
if (element.dataset.src) {
element.src = element.dataset.src;
}
// Optional: handle responsive images
if (element.dataset.srcset) {
element.srcset = element.dataset.srcset;
}
// We're done with this element, stop observing it.
observer.unobserve(element);
}
});
}, {
// Start loading images when they are 200px away from the viewport
rootMargin: '200px',
});
lazyElements.forEach(img => observer.observe(img));
The trap: Forgetting to call observer.unobserve(element). If you don't, the callback will keep firing every time the element intersects, even after the image has loaded. This is a waste of main-thread time, especially on long, scrollable pages.
You Must Prevent Layout Shift
Lazy loading is the most common cause of Cumulative Layout Shift (CLS). When an image loads, it pushes content below it down, creating a jarring "jump". This is a poor user experience and negatively impacts your Core Web Vitals score.
The fix is to reserve space for the image before it loads.
-
Use
widthandheightattributes. For<img>tags, always providewidthandheightattributes. Modern browsers use these to calculate the aspect ratio and reserve the correct amount of space, even if CSS resizes the image. This is the simplest and most robust method. -
Use the CSS
aspect-ratioproperty. This is the modern CSS-only approach. It's great for media containers or elements where you can't set HTML attributes..image-container { aspect-ratio: 16 / 9; background-color: #eee; /* Placeholder color */ }
Mentioning CLS and its solutions shows you think about the full user experience, not just the network optimization.
How to Structure Your Interview Answer
When asked to design a system with many images (like a product feed or gallery), walk through these steps. The following diagram shows the IntersectionObserver flow.
- State the goal: "To improve initial load time and save user bandwidth, I'll lazy load all media that is not 'above the fold'."
- Identify critical content: Explicitly state that you will not lazy load the LCP element (e.g., the main hero image) or any other content visible in the initial viewport. This is a key sign of seniority.
- Propose the solution: "My default choice would be the native
loading="lazy"attribute on<img>tags. It's the most performant solution. I would ensure every image haswidthandheightattributes to prevent layout shift." - Introduce the advanced option: "If we need to support older browsers, lazy load background images, or have custom loading triggers, I'd use the
IntersectionObserverAPI. I'd set arootMarginof around 200-300px to start loading images before they enter the viewport, providing a smoother experience." - Address the user experience: "While the image loads, I'd prevent CLS using the
aspect-ratioCSS property on a container. To improve perceived performance, I'd also show a placeholder. This could be a simple background color, or a more advanced technique like a blurred, low-quality image placeholder (LQIP) that is inlined in the initial HTML."
Try it
Take a content-heavy page you've built and implement lazy loading for all images below the fold using IntersectionObserver. Use your browser's network tab (with caching disabled) to verify that images are only fetched as you scroll. Then, use the Performance panel to check for any layout shifts.
Next: Video Streaming: HLS, DASH, Adaptive Bitrate
Lock it in — apply this lesson under interview conditions.