最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is a ResizeObserver more efficient than a window 'resize' event listener in case of no layout recal

programmeradmin0浏览0评论

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论