ResizeObserver tells you when an element's size changes. MutationObserver tells you when the DOM tree changes.
ResizeObserver notifies you when an element's size changes, for any reason:
- a window resize
- a sibling growing
- content loading
- a CSS change
The resize event on window only covers the viewport. ResizeObserver is for components that adapt to their own size, such as charts, virtualised lists or text truncation. It also saves you from polling offsetWidth.
MutationObserver notifies you when the DOM tree changes:
- children are added or removed
- attributes change
- text changes
It can optionally watch a whole subtree. The browser batches the callbacks and runs them as microtasks. It is useful for reacting to DOM changes made by third-party code, and in browser extensions and tooling. It replaced the old, slow mutation events.
Disconnect both observers when you no longer need them. This avoids memory leaks and wasted work.
- ResizeObserver reports changes to an element's size, not just the window's size.
- MutationObserver reports changes to DOM children, attributes and text.
- MutationObserver callbacks are batched and run as microtasks.
- Disconnect both observers when you are done.