Browsers offer a family of observers: objects that watch something and call your function when it changes. You have met IntersectionObserver, which watches visibility. This lesson covers two more. ResizeObserver tells you when an element changes size, even when the window does not, and MutationObserver tells you when the page’s HTML changes: elements added or removed, or attributes changed.
In this lesson you will learn
- Watching an element’s size with
ResizeObserver - The difference between element size and window size
- Watching DOM changes with
MutationObserver - The
childList,attributesandsubtreeoptions - Stopping observers and avoiding endless loops
You should know DOM manipulation and events.
ResizeObserver
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ResizeObserver</title>
<style>
body { font-family: sans-serif; margin: 12px; font-size: 14px; }
#box {
resize: horizontal; overflow: auto; /* drag the bottom-right corner */
width: 260px; min-width: 120px; max-width: 100%;
padding: 10px; border: 2px solid #7e57c2; border-radius: 8px; background: #ede7f6;
}
#box.compact { background: #fff8e1; border-color: #ffb300; }
</style>
</head>
<body>
<div id="box">Drag my corner to resize me.</div>
<p><b id="size"></b> · <span id="calls"></span></p>
<script>
var box = document.getElementById("box");
var calls = 0;
var observer = new ResizeObserver(function (entries) {
for (var entry of entries) {
var width = Math.round(entry.contentRect.width); // content box, without padding
document.getElementById("size").textContent = width + " px wide";
// Change the element's style based on its own size
entry.target.classList.toggle("compact", width < 200);
}
document.getElementById("calls").textContent = "callbacks so far: " + (++calls);
});
observer.observe(box); // also fires once straight away with the starting size
</script>
</body>
</html>
Result
- Drag the box’s bottom-right corner. The callback runs each time its size changes and receives an array of entries, one per observed element.
entry.contentRect.widthis the width of the content area, without padding or border.entry.borderBoxSizegives the full outer size if you need it.observe()calls the callback once straight away with the starting size, which is handy for setting up.- The window’s
resizeevent fires only when the whole window changes. An element can change size because of a sidebar opening, new content or a CSS change; onlyResizeObservercatches all of these. - For pure styling, CSS container queries are simpler. Use
ResizeObserverwhen JavaScript needs the size, for example to redraw a canvas chart or choose how many items fit.
MutationObserver
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MutationObserver</title>
<style>
body { font-family: sans-serif; margin: 12px; font-size: 14px; }
#chat { border: 1px solid #ccc; border-radius: 6px; padding: 6px; min-height: 60px; }
#chat p { margin: 3px 0; }
#log { font-family: monospace; font-size: 12px; color: #455a64; white-space: pre-line; }
</style>
</head>
<body>
<div id="chat"><p>Welcome to the class chat.</p></div>
<button id="add">New message</button>
<button id="edit">Mark first as read</button>
<button id="clear">Clear</button>
<p id="log"></p>
<script>
var chat = document.getElementById("chat");
var log = document.getElementById("log");
var n = 0;
var observer = new MutationObserver(function (records) {
records.forEach(function (r) {
if (r.type === "childList") {
log.textContent += "childList: +" + r.addedNodes.length + " / -" + r.removedNodes.length + "\n";
} else if (r.type === "attributes") {
log.textContent += "attribute changed: " + r.attributeName + "\n";
}
});
});
// Choose what to watch: added/removed children, attributes, the whole subtree
observer.observe(chat, { childList: true, attributes: true, subtree: true });
document.getElementById("add").onclick = function () {
var p = document.createElement("p");
p.textContent = "Message " + (++n);
chat.append(p);
};
document.getElementById("edit").onclick = function () {
chat.firstElementChild && chat.firstElementChild.setAttribute("data-read", "yes");
};
document.getElementById("clear").onclick = function () {
chat.replaceChildren(); // removes every child in one change
};
</script>
</body>
</html>
Result
- Click the buttons and watch the log. Each callback receives a list of mutation records describing what changed.
- The options say what to watch:
childListfor added and removed child nodes,attributesfor attribute changes, andsubtreeto include all descendants, not just direct children. record.addedNodesandrecord.removedNodeslist the nodes involved;record.attributeNamenames the changed attribute. AddattributeFilter: ["class"]to watch only certain attributes, orcharacterData: trueto watch text changes.- Callbacks are batched: several changes made in the same moment arrive together in one call, after the current script finishes.
replaceChildren()with no arguments removes every child as one record. - Typical uses include reacting to content added by another script or a third-party widget, auto-scrolling a chat when messages arrive, and browser extensions that adjust pages.
The Observer Family
| Observer | Watches | Example use |
|---|---|---|
IntersectionObserver | Visibility in the viewport or a container | Lazy loading, infinite scroll |
ResizeObserver | Element size | Responsive charts and canvases |
MutationObserver | DOM structure and attributes | Reacting to added content |
PerformanceObserver | Performance measurements | Recording Core Web Vitals |
All of them share the same pattern: create with a callback, call observe(target, options), and stop with unobserve(target) or disconnect().
Common Mistakes
- Changing what you observe inside the callback. A ResizeObserver callback that resizes the same element, or a MutationObserver that edits the watched DOM, can trigger itself again and again. Change something else, or disconnect first.
- Watching the whole document with
subtree: truewhen only one area matters, which wastes work on busy pages. - Never calling
disconnect()when a component is removed, leaving observers running. - Using MutationObserver to watch your own code’s changes. If your code makes the change, just call the follow-up function directly.
Practice Exercises
Exercise 1. Log a message whenever #sidebar becomes narrower than 200px.
Show answer
new ResizeObserver(([entry]) => {
if (entry.contentRect.width < 200) console.log("Sidebar is narrow");
}).observe(document.getElementById("sidebar"));
Exercise 2. Keep a chat box scrolled to the bottom whenever a new message is added to it.
Show answer
const chat = document.getElementById("chat");
new MutationObserver(() => {
chat.scrollTop = chat.scrollHeight; // scrolling does not change the DOM, so no loop
}).observe(chat, { childList: true });
Frequently Asked Questions
What does “ResizeObserver loop completed with undelivered notifications” mean?
Your callback changed sizes again, so more resize notifications were waiting when the browser finished the frame. It is a warning, not a crash, but it usually means the callback is resizing the elements it observes.
Are observers better than old events like DOMNodeInserted?
Yes. The old mutation events fired synchronously for every single change and slowed pages badly. They are deprecated, and Chrome has already removed them. MutationObserver replaced them with efficient, batched callbacks.
Summary
ResizeObserverreports element size changes, not just window resizes.MutationObserverreports added and removed nodes and attribute changes.- Choose what to watch with
childList,attributesandsubtree. - Avoid changing the observed thing inside the callback, and disconnect when done.
