← Back to JavaScript, page 8

javascript-0147 · Medium mid

What is IntersectionObserver, and how do you use it for lazy loading images and infinite scroll?

IntersectionObserver reports asynchronously when a target element enters or leaves the viewport (or another root element), without scroll event handlers or layout reads. You create it with a callback and options (root, rootMargin, threshold), call observe on elements, and read isIntersecting and intersectionRatio from the entries. Typical uses are lazy loading, infinite scroll sentinels, and visibility analytics. Unobserve elements once their work is done.

Full answer

Before IntersectionObserver, code listened to scroll events and called getBoundingClientRect(), which forces layout and runs very often. The observer lets the browser compute visibility efficiently and notify you only when it changes.

Usage: const observer = new IntersectionObserver(callback, options), then observer.observe(element). The callback receives entries (one per element whose state changed) and the observer. Each entry has isIntersecting, intersectionRatio (from 0 to 1), target, boundingClientRect, and time.

Options:

  • root: the element used as the viewport. The default null is the browser viewport.
  • rootMargin: grows or shrinks the root box, like CSS margin, for example '200px' to start loading before an image is on screen.
  • threshold: a number or array of ratios at which to call back. 0 (default) means as soon as one pixel is visible, 1 means fully visible, and [0, 0.5, 1] reports at several steps.

Lazy loading images: put the real URL in data-src, observe each image, and when isIntersecting is true, set src from data-src and call unobserve. For simple cases, the native loading="lazy" attribute on img and iframe needs no JavaScript, so prefer it, and keep the observer for background images, videos, and custom behavior.

Infinite scroll: place a small sentinel element at the end of the list. When it intersects, load the next page, append items, and move the sentinel (the observer fires again if it is still visible). Guard against duplicate loads with a loading flag, and offer a way to reach the footer.

Details: the callback runs asynchronously, and the first call happens right after observe with the initial state. Call disconnect() when the component is removed, otherwise the observer keeps references. Elements with display: none never intersect. It does not report exact scroll positions, and sticky or transformed elements may behave in unexpected ways. Test with fakes, since jsdom has no layout engine.

Related: ResizeObserver for size changes and MutationObserver for DOM changes.

javascript
// jsdom has no layout engine, so it has no IntersectionObserver. This fake lets the logic be tested.
class FakeIntersectionObserver {
  static instances = [];
  constructor(callback, options = {}) {
    this.callback = callback;
    this.options = options;
    this.targets = new Set();
    FakeIntersectionObserver.instances.push(this);
  }
  observe(target) { this.targets.add(target); }
  unobserve(target) { this.targets.delete(target); }
  disconnect() { this.targets.clear(); }
  // test helper: pretend that these elements changed visibility
  trigger(changes) {
    const entries = changes
      .filter(([target]) => this.targets.has(target))
      .map(([target, isIntersecting]) => ({ target, isIntersecting, intersectionRatio: isIntersecting ? 1 : 0 }));
    this.callback(entries, this);
  }
}

// logic under test: receives the observer class, so it works with the real one and the fake
function lazyLoadImages(root, Observer) {
  const observer = new Observer((entries, obs) => {
    for (const entry of entries) {
      if (!entry.isIntersecting) continue;
      const img = entry.target;
      img.src = img.dataset.src;
      img.removeAttribute('data-src');
      obs.unobserve(img);
    }
  }, { rootMargin: '200px 0px' });
  root.querySelectorAll('img[data-src]').forEach((img) => observer.observe(img));
  return observer;
}

function infiniteScroll(list, sentinel, loadPage, Observer) {
  let page = 0;
  let loading = false;
  const observer = new Observer(async (entries) => {
    if (!entries.some((entry) => entry.isIntersecting) || loading) return;
    loading = true;
    for (const text of await loadPage(++page)) {
      const li = document.createElement('li');
      li.textContent = text;
      list.append(li);
    }
    loading = false;
  });
  observer.observe(sentinel);
  return observer;
}

document.body.innerHTML = `
  <img id="a" data-src="/photos/a.jpg" alt="A">
  <img id="b" data-src="/photos/b.jpg" alt="B">
  <ul id="list"></ul><div id="sentinel"></div>`;
const [a, b] = [document.getElementById('a'), document.getElementById('b')];

const lazy = lazyLoadImages(document, FakeIntersectionObserver);
console.log('observed:', lazy.targets.size, '| options:', JSON.stringify(lazy.options), '| src before:', a.getAttribute('src'));
lazy.trigger([[a, true], [b, false]]);
console.log('a loaded:', a.getAttribute('src'), '| b waiting:', b.getAttribute('src'), '| still observed:', lazy.targets.size);
lazy.trigger([[a, true]]);
console.log('already loaded image is ignored:', lazy.targets.size);
lazy.trigger([[b, true]]);
console.log('b loaded:', b.getAttribute('src'), '| observed:', lazy.targets.size);

const list = document.getElementById('list');
const sentinel = document.getElementById('sentinel');
let calls = 0;
const loadPage = async (page) => (calls++, [`item ${page}.1`, `item ${page}.2`]);
const scroller = infiniteScroll(list, sentinel, loadPage, FakeIntersectionObserver);

(async () => {
  scroller.trigger([[sentinel, true]]);
  scroller.trigger([[sentinel, true]]); // a second event while loading is ignored
  await new Promise((resolve) => setTimeout(resolve, 5));
  console.log('after two triggers during one load:', list.children.length, 'items, page loads:', calls);
  scroller.trigger([[sentinel, false]]);
  scroller.trigger([[sentinel, true]]);
  await new Promise((resolve) => setTimeout(resolve, 5));
  console.log('next page:', [...list.children].map((li) => li.textContent).join(', '));
  scroller.disconnect();
  console.log('disconnected, observed:', scroller.targets.size, '| real IntersectionObserver in jsdom:', typeof IntersectionObserver);
})();

Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output. Output: observed: 2 | options: {"rootMargin":"200px 0px"} | src before: null a loaded: /photos/a.jpg | b waiting: null | still observed: 1 already loaded image is ignored: 1 b loaded: /photos/b.jpg | observed: 0 after two triggers during one load: 2 items, page loads: 1 next page: item 1.1, item 1.2, item 2.1, item 2.2 disconnected, observed: 0 | real IntersectionObserver in jsdom: undefined

Key points

  • The observer reports visibility changes asynchronously, replacing scroll handlers and layout reads.
  • Options: root, rootMargin to load early, threshold for ratios.
  • Lazy loading: swap data-src to src on intersection and unobserve; native loading="lazy" is simpler for images.
  • Infinite scroll uses a sentinel element, a loading flag, and attention to accessibility.
  • Disconnect when done; test with a fake because jsdom has no layout.

Common mistakes

  • Using scroll events and getBoundingClientRect for visibility checks.
  • Never calling unobserve or disconnect, which keeps elements and callbacks alive.
  • Triggering several page loads at once because there is no loading guard.
  • Ignoring native loading="lazy" for simple image lazy loading.

Follow-ups

  • How does rootMargin help to load content before it is visible?
  • How would you use thresholds to measure how long an ad is visible?
  • How is ResizeObserver different, and when would you use it?

Tips

  • Contrast with scroll handlers: asynchronous and efficient.
  • Give both use cases: lazy loading and a sentinel for infinite scroll.
  • Mention native lazy loading and accessibility for infinite lists.