JavaScript Interview Question #169
What is ResizeObserver?
Performance, Browser APIs, Rendering & Modern Web Architecture Senior Advanced
Quick Interview Answer
ResizeObserver reports changes to the dimensions of observed elements. It allows components to respond to their actual rendered size rather than relying only on global window resize events.
Detailed Explanation
ResizeObserver reports changes to the dimensions of observed elements. It allows components to respond to their actual rendered size rather than relying only on global window resize events.
It is useful for responsive components, charts, editors, and widgets whose layout depends on their container size. Callbacks should avoid creating resize feedback loops by repeatedly changing the observed dimensions without control.
Code Example
const panel = document.querySelector(".panel");
const observer = new ResizeObserver(entries => {
for (const entry of entries) {
console.log(
entry.contentRect.width,
entry.contentRect.height
);
}
});
observer.observe(panel);