MutationObserver callbacks are called synchronously or asynchronously as tasks or microtasks? What if an exception is thrown?
Automation scripts and browser extensions monitor changes in the DOM to simulate user actions or adjust displayed contents.
MutationObserver
is the only API intended for DOM monitoring. Before it was possible to observe changes in the DOM of a web page using mutation events such as DOMNodeInserted or DOMNodeRemoved but they were removed in Chrome 127.
To use MutationObserver
effectively, it is helpful to know how callbacks are called — synchronously or asynchronously, and what happens if an exception is thrown in the callback.
The DOM specification details the behaviour of MutationObserver
. It is clear that callbacks are executed as microtasks, but overall the section about mutation observers is complicated to understand.
In this post I experimentally explore the mechanics of MutationObserver
using a simple code.
The script first schedules one task, one microtask, then it adds several text nodes and finally again creates a task and a microtask. When the observer callback is called an exception is thrown.
function callback(mutations) {…