Belajar
← All lessons

How lazy loading works

Load what the reader will see

article.html

<img src="photo-1.jpg"><img src="photo-2.jpg"> <!-- width and height reserve the space --><img src="photo-3.jpg" loading="lazy"     width="800" height="600">

browser.js

// what the browser does with each <img>for (const img of document.images) {  if (img.loading !== "lazy") fetch(img.src);  else whenNearViewport(img, () => fetch(img.src));}

IntersectionObserver scroll and watch it fire

LoadingEagerLazy
rootMargin0px
Scroll this box
photo-1.jpg · 84 KB
photo-2.jpg · 120 KB
photo-3.jpg · 96 KB
photo-4.jpg · 140 KB
photo-5.jpg · 72 KB
photo-6.jpg · 110 KB
photo-7.jpg · 130 KB
photo-8.jpg · 88 KB
photo-9.jpg · 102 KB
photo-10.jpg · 150 KB
photo-11.jpg · 76 KB
photo-12.jpg · 118 KB
images loaded
downloaded
Observer callbacks

    lazy-images.js

    const io = new IntersectionObserver((entries) => {  for (const e of entries) {    if (!e.isIntersecting) continue;    e.target.src = e.target.dataset.src; // swap in the real src once it's close    io.unobserve(e.target); // loaded, stop watching  }}, {  root: scroller,  rootMargin: `0px 0px ${margin}px 0px`, // start this many px before it shows up});document.querySelectorAll("img[data-src]")  .forEach((img) => io.observe(img));

    Code splitting with import()

    Chart load with import()
    Editor load with import()
    PDF report load with import()
    Build output
    First load
    Downloaded after clicks
    Never downloaded

      app.js

      // always in the first downloadimport { renderChart } from "./chart.js"; // a separate chunk, fetched on the first clickbutton.onclick = async () => {  const { renderChart } = await import("./chart.js");  renderChart(data);};

      Topics

      Next: How promises work

      Open lesson