A resize event on the window misses most size changes: a sidebar that collapses, text that loads, a panel someone drags. ResizeObserver watches the element itself.
const chart = document.querySelector("#chart");
const observer = new ResizeObserver((entries) => {
for (const entry of entries) {
const width = entry.contentBoxSize[0].inlineSize;
redrawChart(width);
}
});
observer.observe(chart);
// later: observer.unobserve(chart) or observer.disconnect()
The callback gets a list of entries, one per observed element that changed. contentBoxSize holds the size of the content area; borderBoxSize includes padding and border. They are arrays because an element split over several columns can have more than one box, so for normal elements index 0 is the one to take. It also fires once right after you call observe(), which gives you the initial size for free.
I like it for canvas charts and for text that should switch to a short version when its container gets narrow. For pure styling, CSS container queries are simpler and need no script.
The trap is a loop. If the callback changes the size of the element it observes, the browser has to call it again. It stops the cycle and reports a “ResizeObserver loop completed with undelivered notifications” error, which you then see in error monitoring. Change other elements, or make sure the change does not affect the observed size.
All current browsers support it; Safari since 13.1.
Further reading: MDN: ResizeObserver, MDN: ResizeObserverEntry