Long pages can spend bandwidth on recommendations that visitors never scroll far enough to read. IntersectionObserver lets a page lazy-load that content when its placeholder approaches the viewport, keeping the initial page focused on what is already visible.

A placeholder reserves space while the browser fetches a separate HTML fragment. A positive rootMargin starts the request slightly before the panel comes into view; stopping observation on the first intersection prevents later scrolls from fetching it again.

Lazy loading suits supplementary content rather than essential information or navigation. HTML inserted into the page must come from a trusted source, and requests need an HTTP server rather than a directly opened local file. A text editor, a browser, and Python 3 are enough to build and run the page.

Steps to lazy-load content with IntersectionObserver:

  1. Create index.html in a new folder using your text editor.
    index.html
    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Lazy content</title>
      <link rel="stylesheet" href="style.css">
      <script src="lazy.js" defer></script>
    </head>
    <body>
      <main>
        <header class="intro">
          <h1>Lazy content</h1>
          <p>Scroll down to load the recommended reading.</p>
        </header>
        <section data-lazy-content data-src="partials/recommendations.html"
                 aria-label="Recommended reading" aria-busy="false">
          <p>Recommendations have not loaded yet.</p>
        </section>
        <noscript>Enable JavaScript to load the recommendations.</noscript>
      </main>
    </body>
    </html>

    data-src names the fragment relative to the page URL. The defer attribute runs lazy.js after the HTML has been parsed, so the placeholder exists before observation starts.
    Related: How to load JavaScript with defer
    Related: How to add a noscript fallback for JavaScript-disabled browsers

  2. Create style.css beside index.html with space above the panel and a visible loaded state.
    style.css
    body {
      margin: 0;
      color: #1e293b;
      background: #f8fafc;
      font: 18px/1.5 system-ui, sans-serif;
    }
    main { max-width: 34rem; margin: auto; padding: 2rem; }
    .intro { min-height: 180vh; }
    [data-lazy-content] {
      min-height: 12rem;
      border: 2px dashed #94a3b8;
      padding: 1.5rem;
    }
     
    [data-lazy-content].is-loaded {
      border-color: #16a34a;
      background: #f0fdf4;
    }

    The tall header puts the placeholder below the initial viewport so scrolling can trigger the request. The panel's minimum height reserves space while it loads; its loaded class changes the border and background to green.

  3. Create partials/recommendations.html inside the same folder with the content to load later.
    partials/recommendations.html
    <h2>Recommended reading</h2>
    <p>This panel was fetched as it approached the viewport.</p>
    <ul>
      <li>Reserve space for content that loads later.</li>
      <li>Keep essential information in the initial HTML.</li>
    </ul>

    partials is a subfolder beside index.html. The response contains only the panel's HTML, without another document's head or body.

  4. Create lazy.js beside index.html with a function that fetches the fragment.

    innerHTML can execute malicious markup. Only insert HTML you control, such as this authored fragment; same-origin hosting alone does not make user-generated content safe.

    lazy.js
    async function loadLazyContent(panel) {
      panel.setAttribute("aria-busy", "true");
     
      try {
        const response = await fetch(panel.dataset.src);
     
        if (!response.ok) {
          throw new Error(`Request failed with ${response.status}`);
        }
        panel.innerHTML = await response.text();
        panel.classList.add("is-loaded");
      } catch (error) {
        panel.textContent = "Recommendations could not be loaded. Reload to try again.";
        console.error(error);
      } finally {
        panel.setAttribute("aria-busy", "false");
      }
    }

    fetch() does not reject on HTTP errors such as 404, so response.ok is checked before insertion. The finally block clears aria-busy after either success or failure.

  5. Append the observer setup after loadLazyContent() in lazy.js.
    const lazyPanels = document.querySelectorAll("[data-lazy-content]");
     
    if ("IntersectionObserver" in window) {
      const observer = new IntersectionObserver((entries, observer) => {
        for (const entry of entries) {
          if (!entry.isIntersecting) continue;
          observer.unobserve(entry.target);
          loadLazyContent(entry.target);
        }
      }, {
        root: null,
        rootMargin: "200px 0px",
        threshold: 0
      });
      lazyPanels.forEach((panel) => observer.observe(panel));
    } else {
      lazyPanels.forEach(loadLazyContent);
    }

    root: null uses the viewport. rootMargin: “200px 0px” extends it above and below, while threshold: 0 lets the first intersection trigger loading. A larger margin gives a slow request more time, but cannot guarantee completion before the panel becomes visible.
    unobserve() stops watching the panel before the request starts, preventing duplicate requests while it is loading or after it succeeds. A failed request leaves a message until reload. Browsers without IntersectionObserver fetch immediately instead.
    Related: IntersectionObserver options

  6. Start an HTTP server from the folder containing index.html.
    $ python3 -m http.server 8000 --bind 127.0.0.1

    The server listens only on your computer. Its terminal stays open while you use the page; on Windows, py -m http.server 8000 –bind 127.0.0.1 works with the Python launcher.

  7. Open http://127.0.0.1:8000/ in your browser.
  8. Scroll down toward the recommended reading panel.

    The page initially shows its heading and scroll instruction. The fragment is requested only when its placeholder reaches the expanded viewport.

  9. Confirm that the green panel displays Recommended reading and both list items.

    The visible content comes from partials/recommendations.html. If an error message appears, the server terminal shows whether that path returned 404; a directly opened file: URL cannot supply this HTTP request.

Share this guide