← Back to Frontend, page 3

frontend-0051 · Easy fresher

How does IntersectionObserver work, and how do you use it for lazy loading and infinite scroll instead of a scroll listener?

IntersectionObserver calls a callback when a watched element enters or leaves the viewport, or another root, by a given amount. The browser does the measuring, off your scroll handler, so it is cheaper and simpler than reading positions in a scroll event. Watch a sentinel element at the end of a list to load the next batch.

Full answer

A scroll listener runs on every scroll event, and reading getBoundingClientRect() inside it can force layout again and again. IntersectionObserver moves the work to the browser. You describe what to watch, and it reports changes.

Creating one: new IntersectionObserver(callback, options), then observer.observe(element). The callback receives a list of entries. Each entry has isIntersecting, intersectionRatio, target and boundingClientRect.

Options:

  • root: the scrolling container to use. The default null is the viewport.
  • rootMargin: grows or shrinks the root box, like CSS margin. A value such as '200px' fires before the element is visible, which hides loading delay.
  • threshold: the fraction of the target that must be visible, such as 0, 0.5 or an array.

Use cases:

  • Lazy loading images and components just before they are needed. For images, the loading="lazy" attribute does this natively and is simpler, but an observer lets you control more (data fetching, widgets, videos).
  • Infinite scroll: put a small sentinel element after the last item. When it intersects, load the next page and append items, and the sentinel moves down.
  • Analytics: record that an ad or a section was seen.
  • Highlighting the active section in a table of contents.

Care points:

  • Call unobserve or disconnect when done, to avoid leaks and repeated loads.
  • Guard against loading twice while a request is running.
  • Infinite scroll has costs for keyboard users who cannot reach the footer, and for memory. Offer a "Load more" button or pagination, and consider list virtualisation for very long lists.
  • The callback runs asynchronously, so the first call comes shortly after observe.

The page below has 10 rows of 100 pixels and a sentinel. The observer adds 10 more rows when the sentinel comes within 200 pixels of the viewport, up to 30. The test scrolls and counts the rows.

html
<style>
  body { margin: 0; }
  .row { height: 100px; border-bottom: 1px solid #ddd; }
</style>
<div id="list"></div>
<div id="sentinel"></div>
<script>
  let count = 0;
  function addRows(n) {
    for (let i = 0; i < n; i++) {
      const row = document.createElement('div');
      row.className = 'row';
      row.textContent = 'Row ' + (++count);
      list.append(row);
    }
  }
  addRows(10);
  const observer = new IntersectionObserver((entries) => {
    if (!entries[0].isIntersecting) return;
    if (count < 30) addRows(10);
    else observer.disconnect();
  }, { rootMargin: '200px' });
  observer.observe(sentinel);
</script>

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. The check scrolled the page by script and counted rows after each step: 10, 20, then 30, and then no more. Scroll by a real touch device was not tested.

Key points

  • The browser reports when watched elements cross the viewport or a root.
  • Options: root, rootMargin and threshold.
  • Use a sentinel element for infinite scroll.
  • Use rootMargin to load before the element is visible.
  • Unobserve when done and guard against duplicate loads.

Common mistakes

  • Using a scroll listener with getBoundingClientRect on every event.
  • Forgetting that the callback also fires once at the start.
  • Not stopping when there is no more data, which loads forever.
  • Infinite scroll with no keyboard-friendly way to reach the footer.

Follow-ups

  • When is loading="lazy" enough?
  • How would you load the next page only once?
  • What does a threshold of 0.5 mean?

Tips

  • Contrast it with a scroll listener in one sentence.
  • Name the three options and give a use for rootMargin.