Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
Frontend System Design Roadmap
  1. 1.HTTP/1.1 vs HTTP/2 vs HTTP/3 (QUIC)
  2. 2.TCP and TLS Handshakes: Connection Setup Costs
  3. 3.Browser Network Stack and Connection Pooling
  4. 4.GET vs POST and Idempotency in HTTP
  5. 5.The Critical Rendering Path (CRP)
  6. 6.DOM, CSSOM and the Render Tree
  7. 7.Layout, Paint and Compositing
  8. 8.Reflows and Repaints Explained
  9. 9.Event Loop: Call Stack, Task and Microtask Queues
  10. 10.Async JavaScript: Promises and async/await
  11. 11.Web Workers: Multi-threading in the Browser
  12. 12.Browser Storage: Cookies, Web Storage, IndexedDB
  13. 13.Client-Side Storage: Limits and Security Risks
  14. 14.Choosing the Right Client-Side Storage
  15. 15.HTTP Caching: Cache-Control, ETag, Last-Modified
  16. 16.Browser-Level Caching Mechanisms
  17. 17.Cache Invalidation for Frontend Apps
  18. 18.Structuring a Large Single-Page App
  19. 19.Component-Based Architecture Principles
  20. 20.Props, State and Component Lifecycle
  21. 21.Module Bundling Basics
  22. 22.Core Web Vitals: LCP, INP and CLS
  23. 23.FCP and Time to Interactive (TTI) Explained
  24. 24.Measuring Performance: Lighthouse and WebPageTest
  25. 25.Asset Compression and Minification Basics
  26. 26.What Is a CDN and How Does It Work?
  27. 27.CDN Benefits: Latency, Availability, Offload
  28. 28.CDN Cache Behavior and Invalidation
  29. 29.Global State vs Local Component State
  30. 30.State Patterns: Redux, Zustand and Context
  31. 31.Data Fetching: React Query and SWR
  32. 32.Immutable Data in Frontend State
  33. 33.SSR vs CSR: Rendering Trade-offs
  34. 34.Hydration and Time to First Byte (TTFB)
  35. 35.Static Site Generation (SSG) for Speed and SEO
  36. 36.Incremental Static Regeneration (ISR)
  37. 37.Micro-Frontends: Core Principles
  38. 38.Micro-Frontend Integration Strategies
  39. 39.Communication Between Micro-Frontends
  40. 40.Micro-Frontends: Pros and Cons for Large Teams
  41. 41.Real-Time: Polling, SSE and WebSockets
  42. 42.Real-Time Use Cases: Chat, Alerts, Live Data
  43. 43.Designing a Real-Time Data Flow
  44. 44.Scaling WebSocket Connections
  45. 45.Responsive Images: srcset, sizes and picture
  46. 46.Modern Image Formats: WebP, AVIF, JPEG XL
  47. 47.Lazy Loading Images and Videos
  48. 48.Video Streaming: HLS, DASH, Adaptive Bitrate
  49. 49.REST and GraphQL for Frontend Engineers
  50. 50.Batching, Throttling and Debouncing API Calls
  51. 51.Handling API Errors in the Frontend
  52. 52.Authentication Flows: OAuth and JWT
  53. 53.Global Error Boundaries in React
  54. 54.Error Reporting: Sentry and LogRocket
  55. 55.Graceful Degradation and Fallback UIs
  56. 56.Real User Monitoring (RUM)
  57. 57.CORS: Cross-Origin Resource Sharing
  58. 58.Preventing XSS (Cross-Site Scripting)
  59. 59.CSRF Protection for Frontend Apps
  60. 60.Content Security Policy (CSP)
  61. 61.Storing Auth Tokens: Cookies vs localStorage
  62. 62.PWA Manifest and Installability
  63. 63.Service Workers: Lifecycle and Caching Strategies
  64. 64.Offline Support and Background Sync
  65. 65.Push Notifications for Web Apps
  66. 66.Webpack vs Vite vs Parcel
  67. 67.Code Splitting, Tree Shaking, Asset Optimization
  68. 68.Module Resolution and Hot Module Replacement
  69. 69.Monorepo Tooling: Nx and Lerna
  70. 70.Atomic Design for Component Libraries
  71. 71.Theming and Customization in Design Systems
  72. 72.Accessibility in Component Libraries
  73. 73.Component Library Docs, Testing and Versioning
  74. 74.Publishing and Consuming a Component Library
  75. 75.Full-Text Search: Levenshtein and Fuzzy Matching
  76. 76.Indexing Large Datasets in the Browser
  77. 77.Search Performance: Debouncing and Web Workers
  78. 78.Integrating Backend Search Services
  79. 79.Choosing a Chart Library: D3, Chart.js, Recharts
  80. 80.Rendering Large Datasets: Canvas vs SVG
  81. 81.Interactive, Responsive Data Visualizations
  82. 82.Data Fetching and Aggregation for Dashboards
  83. 83.A/B Test Design and Rollout Strategies
  84. 84.Client-Side vs Server-Side A/B Testing
  85. 85.Feature Flags and Remote Configuration
  86. 86.Experiment Data Collection and Analytics
Frontend System Design Roadmap
47

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, introduce IntersectionObserver as 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.

  1. Use width and height attributes. For <img> tags, always provide width and height attributes. 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.

  2. Use the CSS aspect-ratio property. 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.

  1. State the goal: "To improve initial load time and save user bandwidth, I'll lazy load all media that is not 'above the fold'."
  2. 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.
  3. 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 has width and height attributes to prevent layout shift."
  4. Introduce the advanced option: "If we need to support older browsers, lazy load background images, or have custom loading triggers, I'd use the IntersectionObserver API. I'd set a rootMargin of around 200-300px to start loading images before they enter the viewport, providing a smoother experience."
  5. Address the user experience: "While the image loads, I'd prevent CLS using the aspect-ratio CSS 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.

Try a free mock interviewPractice system design problems
Previous

Modern Image Formats: WebP, AVIF, JPEG XL

Next

Video Streaming: HLS, DASH, Adaptive Bitrate