DOM & EventsBaseline · Widely

MutationObserver and Batched Microtask Delivery

Mental Model

MutationObserver records DOM insertions, removals, and attribute changes synchronously, then flushes the entire batch as a MutationRecord[] array in a single Microtask before the next paint, eliminating the per-node synchronous thrashing of deprecated Mutation Events.

Interactive Simulator

Batched MutationRecord Queue & Microtask Flush

Trace how synchronous DOM edits batch into one MutationObserver microtask before Paint.

DOM Writes (4)
Record Queue (2)
Microtask Flush
Step 1 / 3: 1. Synchronous DOM Mutations

Script appends 3 nodes and toggles data-state in a loop; no callback fires mid-loop.

list.append(a, b, c);
list.dataset.state = 'ready';
Internal State / Memory
callStack
[ "renderList()" ]
recordQueue
[ "childList(+3)", "attributes(data-state)" ]
callbackFired
false

Under the Hood

Blink appends DOM insertions, removals, and attribute writes to an observer's MutationRecord queue synchronously without invoking JS, then schedules one Microtask to flush the batch once the Call Stack empties. This prevents per-node callback thrashing.

  1. Silent Recording: Each DOM write appends a MutationRecord to the observer's internal queue without pausing JS.
  2. Microtask Checkpoint: When the Call Stack empties, the engine schedules one microtask carrying all queued records.
  3. Targeted Filtering: Passing attributeFilter: ['aria-expanded'] avoids waking JS for unrelated style or class churn.
JS
const mo = new MutationObserver((records) => {
  for (const r of records) {
    if (r.type === 'attributes') syncPanelState(r.target);
  }
});
mo.observe(panel, { attributes: true, attributeFilter: ['data-open'] });

Problem Genealogy

  • 2000 (DOM2 Mutation Events): DOMNodeInserted fired synchronously on every single node, crippling editor performance and causing browser crashes.
  • 2012 (MutationObserver): Batched records asynchronously on the Microtask Queue; Mutation Events were formally removed from browsers in 2024.

Production Pitfalls

Production Pitfall
  • Self-Mutation Microtask Loops: Writing an attribute inside a MutationObserver callback watching that same attribute starves the render loop forever.
  • subtree: true on document.body: Watching the whole document floods your callback during framework hydration; pair with IntersectionObserver for visibility instead.
When Not to Use
  • When not to use MutationObserver: Never use MutationObserver to detect element size or viewport visibility, use ResizeObserver or IntersectionObserver.

Connections & Logical Next Steps

DOM & EventsMutationObserver and Batched Microtask Delivery
What This Unlocks
Leaf concept

Seen in Architecture Autopsies

Mechanical Comparisons