ResizeObserver and MutationObserver
What you'll learn: How to efficiently detect when elements change size or when the DOM structure changes without constantly checking.
The Problem with Polling
Imagine checking your mailbox every five seconds to see if new mail arrived — exhausting and wasteful! The old approach to detecting DOM changes was similar: constantly checking if something happened. Observer APIs flip this model: they notify you when changes occur, like having a doorbell for your mailbox.
ResizeObserver: Watching Size Changes
ResizeObserver monitors elements and fires a callback whenever their dimensions change — perfect for responsive components, canvas resizing, or layout-dependent logic.
const observer = new ResizeObserver((entries) => {
entries.forEach(entry => {
console.log('New size:', entry.contentRect.width, entry.contentRect.height);
// Respond to the size change
});
});
const box = document.querySelector('.my-box');
observer.observe(box);
// Later: stop watching
observer.disconnect();
Each entry contains detailed sizing information about the observed element.
MutationObserver: Watching DOM Changes
MutationObserver detects structural changes: added/removed nodes, attribute changes, text content modifications — anything that alters the DOM tree.
const mutationObserver = new MutationObserver((mutations) => {
mutations.forEach(mutation => {
console.log('Type:', mutation.type);
console.log('Changed nodes:', mutation.addedNodes, mutation.removedNodes);
});
});
const container = document.querySelector('.container');
mutationObserver.observe(container, {
childList: true, // Watch for children added/removed
attributes: true, // Watch attribute changes
subtree: true // Watch descendants too
});
Both observers are asynchronous — callbacks fire after the browser finishes its current task, preventing performance bottlenecks.
Key Takeaway: Use ResizeObserver to react to element size changes and MutationObserver to react to DOM structure changes efficiently, replacing expensive polling loops with event-driven notifications that respect browser performance.