MutationObserver and Batched Microtask Delivery
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.
Batched MutationRecord Queue & Microtask Flush
Trace how synchronous DOM edits batch into one MutationObserver microtask before Paint.
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';- 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.
- Silent Recording: Each DOM write appends a
MutationRecordto the observer's internal queue without pausing JS. - Microtask Checkpoint: When the Call Stack empties, the engine schedules one microtask carrying all queued records.
- Targeted Filtering: Passing
attributeFilter: ['aria-expanded']avoids waking JS for unrelatedstyleorclasschurn.
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):
DOMNodeInsertedfired 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
- Self-Mutation Microtask Loops: Writing an attribute inside a
MutationObservercallback watching that same attribute starves the render loop forever. subtree: trueondocument.body: Watching the whole document floods your callback during framework hydration; pair with IntersectionObserver for visibility instead.
- When not to use
MutationObserver: Never useMutationObserverto detect element size or viewport visibility, useResizeObserverorIntersectionObserver.
Connections & Logical Next Steps
MutationObserver callbacks execute during the Microtask Checkpoint before Update the Rendering.
MutationObserver tracks DOM tree/attribute edits as microtasks; IntersectionObserver tracks post-layout geometry.
Outer MutationObserver instances stop at the ShadowRoot boundary unless attached inside the shadow tree.
Seen in Architecture Autopsies
Mechanical Comparisons
MutationObserver tracks DOM tree/attribute edits as microtasks; IntersectionObserver tracks post-layout geometry.
Outer MutationObserver instances stop at the ShadowRoot boundary unless attached inside the shadow tree.