Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

IntersectionObserver vs ResizeObserver vs MutationObserver: When to Use Each

Scrolling a list, resizing a panel and inserting an item through an external widget are different events. They do not require a shared scroll handler or periodic DOM polling. This guide explains how to choose an observer, interpret notifications and release subscriptions when a component is removed. Each HTML example runs independently in a browser.

Published Written by Reading time 6 min read
On this page Contents: quick navigation between sections

Which observer should you choose?

IntersectionObserver detects crossings of intersection thresholds relative to the viewport or an ancestor. ResizeObserver reacts to changes in an observed box even when the window does not resize. MutationObserver delivers records of node, attribute and character-data changes. They are not interchangeable: a media query can resize a box without changing the DOM, and adding a class need not change its size. [1][2][3]

For styles based on available space, use container queries. For images below the initial viewport, native loading="lazy" is usually sufficient; avoid blindly applying it to the LCP image. A scroll handler can still be appropriate when you need continuous position rather than threshold crossings. [1][8][9]

Each example is independent: put the HTML in the document, the CSS in styles.css and the JavaScript in main.js. Link the stylesheet and load the script as a module (type="module"). The module exports dispose(); call it during component unmount before removing its DOM. Invalid markup produces an explicit initialization error rather than an incidental TypeError.

How can you prepare content before it enters the viewport?

<section class="recommendations" aria-labelledby="recommendations-heading">
  <h2 id="recommendations-heading">Recommendations</h2>

  <div
    id="recommendations-feed"
    class="recommendations__feed"
    role="region"
    aria-label="Recently viewed products"
    tabindex="0"
  >
    <ul class="recommendations__products">
      <li>Wireless keyboard</li>
      <li>USB-C docking station</li>
      <li>Adjustable monitor stand</li>
      <li>Noise-cancelling headphones</li>
    </ul>

    <button id="prepare-recommendations" type="button">
      Prepare recommendations
    </button>
  </div>

  <p id="recommendations-status" role="status">Not prepared yet.</p>
</section>
.recommendations__feed {
  max-block-size: 12rem;
  overflow: auto;
  padding: 1rem;
  border: 1px solid currentColor;
  border-radius: 0.5rem;
}

.recommendations__products {
  display: grid;
  gap: 0.75rem;
  margin-block: 0 1rem;
  padding-inline-start: 1.5rem;
}

.recommendations__products li {
  min-block-size: 6rem;
  padding-block: 0.75rem;
  box-sizing: border-box;
  border-block-end: 1px solid currentColor;
}

.recommendations__feed:focus-visible {
  outline: 2px solid currentColor;
  outline-offset: 3px;
}

.recommendations button[aria-disabled="true"] {
  cursor: default;
}
function prepareOnce({ root, target, onPrepare }) {
  let observer;
  let finished = false;

  function dispose() {
    finished = true;
    observer?.disconnect();
    target.removeEventListener("click", prepare);
  }

  function prepare() {
    if (finished) {
      return;
    }

    dispose();
    onPrepare();
  }

  target.addEventListener("click", prepare);

  if (typeof IntersectionObserver === "function") {
    observer = new IntersectionObserver(
      (entries) => {
        if (entries.some((entry) => entry.isIntersecting)) {
          prepare();
        }
      },
      { root, rootMargin: "0px 0px 120px 0px", threshold: 0 },
    );

    observer.observe(target);
  }

  return dispose;
}

const feed = document.querySelector("#recommendations-feed");
const button = document.querySelector("#prepare-recommendations");
const status = document.querySelector("#recommendations-status");

if (
  !(feed instanceof HTMLElement) ||
  !(button instanceof HTMLButtonElement) ||
  !(status instanceof HTMLElement) ||
  !feed.contains(button)
) {
  throw new Error("Invalid recommendations markup.");
}

export const dispose = prepareOnce({
  root: feed,
  target: button,
  onPrepare() {
    status.textContent = "Recommendations ready.";
    button.setAttribute("aria-disabled", "true");
  },
});

This example prepares recommendations once the button approaches the bottom of its scrolling panel by 120 px. root specifies the scrolling ancestor; null uses the viewport. rootMargin expands the intersection area, so the callback can run before the button actually appears. [1]

The button allows manual activation even without IntersectionObserver. prepareOnce disconnects after use and returns a cleanup function. The demo only updates status; production code can load a module or data here with error handling, retry and cancellation. Pagination additionally needs a concurrent-request guard and an end-of-list condition.

The list uses real content rather than empty spacer elements. After preparation the button remains focusable, but aria-disabled and removal of its listener prevent another action.

Why does a 50% threshold not guarantee full visibility?

<section aria-labelledby="visibility-heading">
  <h2 id="visibility-heading">Product visibility</h2>

  <div
    id="product-viewport"
    class="product-viewport"
    role="region"
    aria-label="Product previews"
    tabindex="0"
  >
    <article class="product-preview">
      <h3>Keyboard</h3>
      <p>Compact wireless model.</p>
    </article>
    <article class="product-preview" id="tracked-product">
      <h3>Monitor stand</h3>
      <p>Height-adjustable model.</p>
    </article>
    <article class="product-preview">
      <h3>Headphones</h3>
      <p>Over-ear model.</p>
    </article>
  </div>

  <p id="product-visibility">Visibility not measured yet.</p>
</section>
.product-viewport {
  display: grid;
  gap: 0.75rem;
  max-block-size: 7rem;
  overflow: auto;
  padding: 0.5rem;
  border: 1px solid currentColor;
}

.product-viewport:focus-visible {
  outline: 2px solid currentColor;
  outline-offset: 3px;
}

.product-preview {
  min-block-size: 5rem;
  box-sizing: border-box;
  padding: 0.75rem;
  border: 1px solid currentColor;
  border-radius: 0.5rem;
}

.product-preview h3,
.product-preview p {
  margin: 0;
}

.product-preview p {
  margin-block-start: 0.25rem;
}
function observeVisibility(root, target, output) {
  if (typeof IntersectionObserver !== "function") {
    output.textContent = "Visibility measurement unavailable.";
    return () => {};
  }

  const minimumVisibleRatio = 0.5;
  let disposed = false;

  const observer = new IntersectionObserver(
    (entries) => {
      if (disposed) {
        return;
      }

      for (const entry of entries) {
        const isMostlyVisible =
          entry.isIntersecting &&
          entry.intersectionRatio >= minimumVisibleRatio;

        output.textContent = String(isMostlyVisible);
      }
    },
    { root, threshold: [0, minimumVisibleRatio] },
  );

  observer.observe(target);

  return () => {
    disposed = true;
    observer.disconnect();
  };
}

const viewport = document.querySelector("#product-viewport");
const product = document.querySelector("#tracked-product");
const visibility = document.querySelector("#product-visibility");

if (
  !(viewport instanceof HTMLElement) ||
  !(product instanceof HTMLElement) ||
  !(visibility instanceof HTMLElement) ||
  !viewport.contains(product)
) {
  throw new Error("Invalid product visibility markup.");
}

export const dispose = observeVisibility(viewport, product, visibility);

threshold: [0, 0.5] generates notifications when the relevant thresholds are crossed in either direction, and upon initial observation. isIntersecting can be true at edge contact with zero intersection area, so also check intersectionRatio when requiring half the area. Process every entry rather than just the first. [1][4]

The ratio describes geometry, not occlusion by another layer, opacity or whether the tab is active. Do not use intersection alone for advertisement exposure accounting. For duration measurement consider the Page Visibility API and your own visibility requirements. [1][10]

If the API is unavailable, the output reports that measurement is unavailable instead of displaying a misleading false value.

How do you measure a panel without a window resize event?

<section aria-labelledby="chart-heading">
  <h2 id="chart-heading">Chart dimensions</h2>
  <button id="toggle-chart-width" type="button" aria-pressed="false">
    Compact chart panel
  </button>

  <div id="chart-frame" class="chart-frame">
    <div id="chart-host" class="chart-frame__content">
      Chart area
    </div>
  </div>

  <p id="chart-dimensions">Dimensions not measured yet.</p>
</section>
.chart-frame {
  box-sizing: border-box;
  inline-size: 24rem;
  max-inline-size: 100%;
  margin-block-start: 1rem;
  border: 1px solid currentColor;
}

.chart-frame--compact {
  inline-size: 18rem;
}

.chart-frame__content {
  display: grid;
  place-items: center;
  min-block-size: 7.5rem;
  padding: 1rem;
}
function observeContentSize(element, onSize) {
  let frameId = null;
  let previousSize;
  let disposed = false;

  const observer = new ResizeObserver((entries) => {
    if (disposed) {
      return;
    }

    const entry = entries.find((record) => record.target === element);

    if (!entry) {
      return;
    }

    const { width, height } = entry.contentRect;

    if (frameId !== null) {
      cancelAnimationFrame(frameId);
    }

    frameId = requestAnimationFrame(() => {
      frameId = null;

      if (
        previousSize?.width === width &&
        previousSize?.height === height
      ) {
        return;
      }

      previousSize = { width, height };
      onSize(previousSize);
    });
  });

  observer.observe(element, { box: "content-box" });

  return () => {
    disposed = true;
    observer.disconnect();

    if (frameId !== null) {
      cancelAnimationFrame(frameId);
      frameId = null;
    }
  };
}

const chartFrame = document.querySelector("#chart-frame");
const toggleButton = document.querySelector("#toggle-chart-width");
const chartHost = document.querySelector("#chart-host");
const dimensions = document.querySelector("#chart-dimensions");

if (
  !(chartFrame instanceof HTMLElement) ||
  !(toggleButton instanceof HTMLButtonElement) ||
  !(chartHost instanceof HTMLElement) ||
  !(dimensions instanceof HTMLElement) ||
  !chartFrame.contains(chartHost)
) {
  throw new Error("Invalid chart markup.");
}

function mountChart() {
  if (typeof ResizeObserver !== "function") {
    dimensions.textContent = "Live measurement unavailable.";
    return () => {};
  }

  return observeContentSize(chartHost, ({ width, height }) => {
    dimensions.textContent = `${width} × ${height} CSS px`;
  });
}

const stopMeasuring = mountChart();

function toggleCompactMode() {
  const compact = chartFrame.classList.toggle("chart-frame--compact");
  toggleButton.setAttribute("aria-pressed", String(compact));
}

toggleButton.addEventListener("click", toggleCompactMode);

export function dispose() {
  stopMeasuring();
  toggleButton.removeEventListener("click", toggleCompactMode);
}

ResizeObserver measures an element such as a chart panel that gets narrower when navigation opens. contentRect supplies physical content dimensions in CSS pixels. Padding and borders are excluded; for logical dimensions use contentBoxSize or borderBoxSize and consider writing modes and fragmentation. [2][5]

The example coalesces notifications into the next animation frame, skips unchanged sizes and updates output outside the observed element. Do not increase the observed element's width in response to every width change. requestAnimationFrame alone cannot remove a cyclic dependency: a loop may continue across frames. [2]

The button toggles panel width through a CSS class and exposes its state via aria-pressed, including for keyboard users. Without ResizeObserver it remains usable and the output explicitly reports that live measurement is unavailable.

How do you react to external widget mutations?

<section aria-labelledby="imports-heading">
  <h2 id="imports-heading">Imported items</h2>

  <ul id="imported-items" class="imported-items">
    <li data-status="pending">Initial import pending</li>
  </ul>

  <button id="simulate-import" type="button">Simulate import</button>
  <p id="import-summary" role="status">Counting ready items…</p>
</section>
.imported-items {
  display: grid;
  gap: 0.5rem;
  padding-inline-start: 1.5rem;
}

.imported-items li {
  padding-block: 0.25rem;
}
function observeReadyItems(root, output) {
  let previousCount = null;
  let disposed = false;

  function updateSummary() {
    if (disposed) {
      return;
    }

    const count = root.querySelectorAll('[data-status="ready"]').length;

    if (count === previousCount) {
      return;
    }

    previousCount = count;
    output.textContent = `Ready items: ${count}`;
  }

  if (typeof MutationObserver !== "function") {
    output.textContent = "Live import tracking unavailable.";
    return () => {};
  }

  const observer = new MutationObserver(updateSummary);

  observer.observe(root, {
    childList: true,
    subtree: true,
    attributes: true,
    attributeFilter: ["data-status"],
  });

  updateSummary();

  return () => {
    disposed = true;
    observer.disconnect();
  };
}

const items = document.querySelector("#imported-items");
const summary = document.querySelector("#import-summary");
const importButton = document.querySelector("#simulate-import");

if (
  !(items instanceof HTMLUListElement) ||
  !(summary instanceof HTMLElement) ||
  !(importButton instanceof HTMLButtonElement) ||
  items.contains(summary)
) {
  throw new Error("Invalid import widget markup.");
}

const stopObserving = observeReadyItems(items, summary);

function simulateImport() {
  const item = document.createElement("li");
  item.dataset.status = "ready";
  item.textContent = "Imported item (ready)";
  items.append(item);
}

importButton.addEventListener("click", simulateImport);

export function dispose() {
  stopObserving();
  importButton.removeEventListener("click", simulateImport);
}

Observe only the widget root, descendant insertions and removals, and the data-status attribute. MutationObserver batches records and delivers them through the microtask mechanism. The example reads the current state after a batch rather than assuming one notification represents one operation. [3][6]

Output is written outside the observed subtree to prevent self-triggering. For large lists, consider incremental updates from records after measuring scan cost. Changing input.value need not change a DOM attribute: use the input event for user edits and the application's own subscription mechanism for state changes.

The button simulates an import by adding a list item. Without MutationObserver the list still works, but the summary explicitly reports that tracking is unavailable.

How do you disconnect observers and diagnose overhead?

<section class="panel-monitoring" aria-labelledby="panel-heading">
  <h2 id="panel-heading">Panel monitoring</h2>
  <article id="monitored-panel" class="monitored-panel">
    <h3>Activity panel</h3>
    <p>Live monitoring example.</p>
  </article>

  <p id="panel-state">Waiting for observations.</p>
  <button id="stop-monitoring" type="button">Stop monitoring</button>
  <p id="monitoring-status" role="status"></p>
</section>
.monitored-panel {
  box-sizing: border-box;
  inline-size: min(100%, 24rem);
  min-block-size: 5rem;
  padding: 1rem;
  border: 1px solid currentColor;
  border-radius: 0.5rem;
}

.monitored-panel h3,
.monitored-panel p {
  margin: 0;
}

.monitored-panel p {
  margin-block-start: 0.5rem;
}

.panel-monitoring button[aria-disabled="true"] {
  cursor: default;
}
function mountPanel(panel, output) {
  const state = { visible: "Pending", width: "Pending" };
  let intersectionObserver;
  let resizeObserver;
  let disposed = false;

  function render() {
    output.textContent =
      `Intersecting: ${state.visible}; content width: ${state.width}`;
  }

  if (typeof IntersectionObserver === "function") {
    intersectionObserver = new IntersectionObserver((entries) => {
      if (disposed) {
        return;
      }

      for (const entry of entries) {
        state.visible = String(entry.isIntersecting);
      }

      render();
    });

    intersectionObserver.observe(panel);
  } else {
    state.visible = "Unavailable";
  }

  if (typeof ResizeObserver === "function") {
    resizeObserver = new ResizeObserver((entries) => {
      if (disposed) {
        return;
      }

      for (const entry of entries) {
        state.width = `${entry.contentRect.width} CSS px`;
      }

      render();
    });

    resizeObserver.observe(panel, { box: "content-box" });
  } else {
    state.width = "Unavailable";
  }

  render();

  return () => {
    if (disposed) {
      return;
    }

    disposed = true;
    intersectionObserver?.disconnect();
    resizeObserver?.disconnect();
  };
}

const panel = document.querySelector("#monitored-panel");
const stateOutput = document.querySelector("#panel-state");
const stopButton = document.querySelector("#stop-monitoring");
const status = document.querySelector("#monitoring-status");

if (
  !(panel instanceof HTMLElement) ||
  !(stateOutput instanceof HTMLElement) ||
  !(stopButton instanceof HTMLButtonElement) ||
  !(status instanceof HTMLElement)
) {
  throw new Error("Invalid monitoring markup.");
}

const stopObserving = mountPanel(panel, stateOutput);

export function dispose() {
  stopObserving();
  stopButton.removeEventListener("click", dispose);
  stopButton.setAttribute("aria-disabled", "true");
  status.textContent = "Monitoring stopped.";
}

stopButton.addEventListener("click", dispose);

The panel mounting function returns idempotent cleanup for both observers. IntersectionObserver and ResizeObserver also provide unobserve() for individual targets. MutationObserver has no such method; disconnect() stops all its observations. If pending mutation records matter, retrieve them with takeRecords() before disconnecting and process them explicitly. [3][7]

In React, set up observation in an effect and return cleanup; elsewhere use the relevant lifecycle. Cancel scheduled frames and requests too. Use the Performance panel to inspect callback counts, script time and layout work with realistic element counts; observer callbacks are not free. [2][11]

Missing support for one API does not block the other; pending and unavailable states are distinct from measured values. The stop button disconnects observation and removes its own listener.

Choose the API according to the actual change: intersection geometry, dimensions or DOM structure. Keep the observation scope small, update only when necessary and release resources with the component lifecycle. For responsive styles or deferred image loading alone, start with CSS or HTML.

JavaScript IntersectionObserver ResizeObserver MutationObserver DOM Web APIs Performance Frontend

Frequently asked questions

Does IntersectionObserver work inside a scrolling panel?

Yes. Pass the scrolling ancestor as root and choose an appropriate margin. The target must be its descendant. [1]

Does ResizeObserver detect a transform translation?

No. A transform alone does not change the observed box size. Use IntersectionObserver for intersection with an area. [2][12]

Does MutationObserver detect every CSS change?

No. It can detect class or style attribute changes, but not computed style changes caused by a media query, for example. [3]

Can one observer watch multiple elements?

Yes. IntersectionObserver and ResizeObserver support multiple targets. Group targets with compatible settings instead of creating unnecessary instances. [1][2]

Sources and references

  1. MDN: Intersection Observer API↩1↩2↩3↩4↩5↩6↩7
  2. MDN: ResizeObserver↩1↩2↩3↩4↩5↩6
  3. MDN: MutationObserver↩1↩2↩3↩4
  4. MDN: IntersectionObserver.observe()↩
  5. MDN: ResizeObserverEntry.contentBoxSize↩
  6. WHATWG: DOM Standard, Mutation observers↩
  7. MDN: MutationObserver.takeRecords()↩
  8. MDN: CSS container queries↩
  9. MDN: Lazy loading↩
  10. MDN: Timing element visibility with Intersection Observer↩
  11. Chrome DevTools: Analyze runtime performance↩
  12. CSSWG: Resize Observer Module Level 1↩

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning