Skip to content
Tutorials Center
My learning

Topics

Lesson 98 of 156 ยท Browser APIs

Intersection, Resize and Mutation Observers

Use IntersectionObserver for lazy loading and infinite scroll, ResizeObserver for size-aware components and MutationObserver to watch the DOM change.

Pages often need to react to things that aren't events in the usual sense. Has this card scrolled into view? Did that panel just get narrower? Did some other script add new items to the list? You could check every few milliseconds, or listen to every scroll and resize event and measure elements by hand, but that is slow, wasteful and easy to get wrong.

Browsers give you three observers for these jobs instead:

  • IntersectionObserver tells you when an element enters or leaves the visible area (or another scrolling box).
  • ResizeObserver tells you when an element's size changes, for any reason.
  • MutationObserver tells you when the DOM itself changes: children added or removed, attributes or text edited.

The browser does the measuring at the right moment and calls you only when something has actually changed. All three share one pattern, so once you know one, the others are easy.

The shared pattern

Every observer works the same way:

JavaScript
// 1. Create it with a callback (and options for some observers)
const observer = new IntersectionObserver((entries, observer) => {
  // 3. The browser calls you with a batch of entries
  for (const entry of entries) {
    console.log(entry.target, entry.isIntersecting);
  }
}, { threshold: 0 });

// 2. Tell it which elements to watch
observer.observe(document.querySelector("#banner"));

// 4. Stop when you're done
observer.unobserve(someElement); // stop watching one element
observer.disconnect();           // stop watching everything

Notice that the callback receives an array. The browser collects changes and delivers them together, so a single call may describe several elements. Always loop over the entries; don't assume there's exactly one. One observer can watch hundreds of elements, which is much cheaper than creating an observer per element.

IntersectionObserver: is it visible?

An IntersectionObserver reports when a target element starts or stops overlapping its root. By default the root is the browser viewport. You can also pass any scrolling element as root, which is what the examples below do, because they scroll inside a small box.

Each entry has the properties you'll use most:

  • entry.target: the element this entry describes.
  • entry.isIntersecting: true if any part of the target overlaps the root.
  • entry.intersectionRatio: how much of the target is visible, from 0 to 1.
  • entry.boundingClientRect and entry.rootBounds: the rectangles that were compared.

The callback also runs once right after you call observe(), reporting the element's starting state. That's handy: an element that is already on screen is handled without waiting for a scroll.

Scroll inside the box below. Cards fade in as they enter and fade out as they leave, and the console shows each change:

Reveal cards as they scroll into view

If you only want the animation to play once, call observer.unobserve(entry.target) as soon as the element becomes visible. The observer stops tracking it, and the work is done for good.

Thresholds and rootMargin

Two options control when the callback fires:

  • threshold is a ratio, or a list of ratios, that must be crossed. 0 (the default) fires as soon as one pixel is visible. 1 fires only when the element is fully visible. [0, 0.25, 0.5, 0.75, 1] fires at every quarter.
  • rootMargin grows or shrinks the root's box, written like the CSS margin property: "200px 0px" starts reporting 200 pixels before the element actually scrolls into view. Negative values do the opposite.
JavaScript
// Fire when at least half of a video is visible
const halfVisible = new IntersectionObserver(callback, { threshold: 0.5 });

// Start loading 300px before the element reaches the viewport
const early = new IntersectionObserver(callback, { rootMargin: "300px 0px" });

isIntersecting ignores your threshold. It is true whenever any part of the element overlaps the root. With threshold: 0.5, the callback also fires when the element drops below half visible, and that entry still says isIntersecting: true. When the threshold matters, test entry.intersectionRatio >= 0.5 instead.

One more detail: when the root is the viewport and your page is inside a cross-origin iframe, the browser ignores rootMargin. Setting an explicit scrolling root, as these examples do, avoids that.

Infinite scroll with a sentinel

A classic use is infinite scroll. Put an empty sentinel element after the last item and observe it. When the sentinel comes close to view, load the next page of items. Because new items push the sentinel down again, the cycle repeats naturally. Here, "loading" is a short setTimeout standing in for a network request:

Infinite scroll with a sentinel element

The loading flag stops a second request from starting while the first is still on its way. If a page of items is too short to push the sentinel out of view, the observer won't fire again, because nothing changed. Real feeds handle this by loading pages big enough to fill the screen, or by checking the sentinel again after each load.

For images, you often don't need any JavaScript: <img loading="lazy"> tells the browser to delay off-screen images by itself (see Responsive Images). Reach for IntersectionObserver when you need custom behavior, such as loading data, starting animations, pausing videos that scroll away or tracking which section a reader is in.

ResizeObserver: how big is it?

The resize event only tells you when the window changes size. But an element can resize for many other reasons: a sidebar opens, text is added, a grid reflows. A ResizeObserver reports the size of the element itself, whatever the cause.

Each entry offers the new size in a few forms:

  • entry.contentRect: a rectangle with width and height of the content box (the original, simplest property).
  • entry.contentBoxSize[0] and entry.borderBoxSize[0]: objects with inlineSize and blockSize. In horizontal writing modes, inline means width and block means height.

Drag the bottom-right corner of the panel to resize it. Below 360 pixels the profile switches to a stacked layout:

A component that adapts to its own width

The panel has a fixed height on purpose. The callback changes the layout inside the panel, and that must not change the size of the panel itself. Otherwise you get the problem described next.

Avoid resize loops. If your callback changes the size of the element you are observing, the browser has to report the new size again, and that could go on forever. Browsers stop after one round per frame and report the error "ResizeObserver loop completed with undelivered notifications". To avoid it, change only things that don't affect the observed element's size, or observe a parent whose size is set from outside.

For pure styling, CSS can often do this job on its own: container queries switch styles based on a container's size with no JavaScript at all. Use ResizeObserver when the change needs code, such as redrawing a <canvas> chart at its new size, choosing how many items fit in a row or recalculating a virtual list.

MutationObserver: did the DOM change?

A MutationObserver watches a part of the DOM tree and reports every change to it. It is useful when other code changes the page and you need to react: a third-party widget inserts content, a framework re-renders a section, or a user edits a contenteditable region.

Unlike the other two observers, it needs options that say what to watch. You must turn on at least one of childList, attributes or characterData:

Option Watches
childList: true Child nodes being added or removed
attributes: true Attribute changes (attributeFilter: ["class"] limits which ones)
characterData: true Changes to the text inside text nodes
subtree: true The same changes on every descendant, not only the target
attributeOldValue: true Keep the attribute's previous value in the record

Each mutation record has a type ("childList", "attributes" or "characterData"), a target, and details such as addedNodes, removedNodes, attributeName and oldValue.

Click the buttons and edit the text, then watch the console. Notice that "Add three" produces one callback containing three records:

Watching the DOM change

Two things are worth knowing about how records arrive:

  • Callbacks run as a microtask, after the current script finishes (see How Asynchronous JavaScript Works). Three changes in one click handler arrive together in one batch, so you never see a half-finished DOM.
  • There is no initial call. A MutationObserver only reports changes made after observe().

MutationObserver has no unobserve(). Call disconnect() to stop, and takeRecords() to grab any records that are queued but not yet delivered, for example right before you disconnect.

Don't create a feedback loop. If your callback changes the part of the DOM it is watching, that change produces new records, which call your callback again. Either change something outside the watched area, or disconnect(), make your change, and observe() again.

When the page is your code, you usually don't need a MutationObserver: the code that changes the DOM can simply call your function. Save it for changes you don't control.

Cleaning up

Observers keep running, and keep their callbacks alive, until you stop them. On a long-lived page or a single-page app, stop them when their job is done:

  • unobserve(element) when one element no longer needs watching, such as after a one-time reveal (Intersection and Resize observers).
  • disconnect() when a component is removed from the page, or when there's nothing left to do, like the end of an infinite feed.

All three observers are supported in every current browser and have been for years, so you can use them without fallbacks.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You want to start loading a section's data 300 pixels before it scrolls into view. Which option do you set?

    rootMargin grows the root's box, so elements count as intersecting before they are actually visible. threshold is a ratio between 0 and 1.
  2. 2. An IntersectionObserver uses threshold: 0.5. An element scrolls from 60% visible to 40% visible. What does the entry report?

    The callback runs because the 0.5 threshold was crossed, but isIntersecting stays true while any part is visible. Check intersectionRatio when the threshold matters.
  3. 3. Which observer should you use to redraw a canvas chart whenever its container changes width?

    ResizeObserver reports an element's own size changes, whatever caused them. The window resize event misses layout changes inside the page.
  4. 4. What happens if you call observer.observe(list) on a MutationObserver with an empty options object?

    A MutationObserver must be told what to watch. Options like attributeFilter or attributeOldValue also turn on attribute watching.
  5. 5. A click handler adds three list items. How does a MutationObserver watching the list report this?

    Mutation records are queued and delivered in a microtask after the current script, so the three changes arrive together.

Summary

  • Observers replace polling and heavy scroll/resize listeners: create one with a callback, observe() targets, handle an array of entries, then unobserve() or disconnect().
  • IntersectionObserver reports visibility against the viewport or a scrolling root. Tune it with threshold and rootMargin, and use it for reveal effects, lazy loading and infinite scroll with a sentinel.
  • isIntersecting ignores thresholds; check intersectionRatio when the exact amount matters.
  • ResizeObserver reports an element's own size (contentBoxSize, borderBoxSize, contentRect). Don't resize the observed element inside its callback, and prefer CSS container queries for pure styling.
  • MutationObserver reports DOM changes you ask for (childList, attributes, characterData, subtree), batched in a microtask, with no initial call.

Next: Files, Blobs and Base64.