The problem it replaces
Older code polled the DOM or used deprecated mutation events that fired synchronously on every change, hurting performance. MutationObserver delivers changes asynchronously and in batches.
What it watches
You configure which mutations matter:
- childList: nodes added or removed.
- attributes: attribute values changing, optionally filtered to specific names.
- characterData: text content changing.
- subtree: extend any of the above to all descendants.
How delivery works
Mutations are queued and the callback runs as a microtask after the current script settles. The callback receives a list of MutationRecord entries describing exactly what changed, including added and removed nodes and old attribute values when requested.
Practical uses
- Reacting to DOM injected by third party scripts or a CMS.
- Keeping a derived index or virtual structure in sync.
- Enforcing invariants, like stripping unwanted attributes.
Cautions
- Because it runs as a microtask, a callback that mutates more DOM can cascade. Disconnect or guard against feedback loops.
- Observing a large subtree with all options can be costly; scope it narrowly.
Key idea
MutationObserver batches DOM change records and delivers them as a microtask, replacing synchronous mutation events and polling.