What is Lazy Loading?

Lazy loading means deferring the loading of a resource (images, iframes, scripts, components or data) until it is actually needed, typically when it is about to scroll into view or when the user interacts.

Native lazy loading in HTML

  • <img loading="lazy"> and <iframe loading="lazy">: the browser fetches them as they approach the viewport.
  • Never lazy-load the main above-the-fold image (the LCP element); it delays the most important content. Use fetchpriority="high" for it instead.
  • Always set width and height (or an aspect ratio) so lazy images do not cause layout shift.

JavaScript lazy loading

  • Code: dynamic import(), React.lazy, next/dynamic (see code splitting).
  • Visibility-based loading: IntersectionObserver to load content, start videos or fetch more data when an element becomes visible (infinite scroll).
  • Interaction-based loading: load a chat widget or editor only on click or hover.
  • Idle loading: requestIdleCallback to warm up things that will be needed later.

Data

Pagination and infinite scroll are lazy loading for data: fetch the next page only when the user gets near the end.

Frameworks

Next.js <Image> lazy-loads by default and has a priority prop for the LCP image. Many frameworks also lazy-load routes automatically.

Trade-offs

Lazy loading saves bandwidth and speeds up the initial load, but content may appear with a delay. Use generous rootMargin to start loading before the element is visible, and show placeholders or skeletons.

Code example

js
1// Load images (or anything) shortly before they scroll into view
2document.body.innerHTML = `
3 <div style="height:120vh">Scroll down</div>
4 <img data-src="https://picsum.photos/seed/lazy/400/200" width="400" height="200" alt="Lazy image" class="lazy">`;
5
6const observer = new IntersectionObserver(
7 (entries, obs) => {
8 for (const entry of entries) {
9 if (!entry.isIntersecting) continue;
10 const img = entry.target;
11 img.src = img.dataset.src; // start the real download now
12 obs.unobserve(img); // load once
13 console.log("loading", img.alt);
14 }
15 },
16 { rootMargin: "300px" } // start 300px before it becomes visible
17);
18document.querySelectorAll("img.lazy").forEach((img) => observer.observe(img));
19
20// Load a feature's code only when the user asks for it
21document.body.insertAdjacentHTML("afterbegin", `<button id="chat">Open chat</button>`);
22document.getElementById("chat").addEventListener(
23 "click",
24 async () => {
25 // const { mountChat } = await import("./chat-widget.js");
26 console.log("chat widget code would be downloaded now");
27 },
28 { once: true }
29);
30
31// Native: <img src="photo.jpg" loading="lazy" width="400" height="300" alt="...">

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app