The following sample code has two callbacks:
let e = 0, r = 0;
new ResizeObserver(() => {
console.log('resized from observer', r++)
}).observe(document.documentElement);
window.addEventListener('resize', () => {
console.log('resized from event', e++);
});
Both of them run the same number of times and at the same timestamps. As an example, the following image shows the output I get in Chrome 130 DevTools when resizing a window very quickly:
(Note: the values are off by one because the ResizeObserver runs once on initialisation, before any resize happens)
Now, it is a well known claim that the ResizeObserver is a more efficient approach to observe resizes. This claim is almost always discussed in the context of layout thrashing - where we read/write layout properties from inside the callback. However, that claim is not applicable to the above case.
Similarly, there is previous discussion about ResizeObserver being more efficient to EventTarget APIs, but it is in the context of a <div>
HTML element, not the Window object itself. So, I do not think that it is applicable in this case.
Question: is the ResizeObserver really more efficient compared to the Window 'resize' event in the case of callbacks that don't have layout recalculation (like the one above)? If yes, how can we verify that using code?
Given the above sample output, I think both are equally efficient. But I am not confident about it.