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

javascript - One intersectionObserver to observe many elements or one intersectionObserver per element - Stack Overflow

programmeradmin0浏览0评论

We have a few CustomElements in our page and some of them have an IntersectionObserver relative to the viewport observing them. That number might be increasing as the designer seems to like intersection animations.

Will that lead to performance issues? Is it better to have one IntersectionObserver that observes all elements or many IntersectionObservers that only observe one element?

We have a few CustomElements in our page and some of them have an IntersectionObserver relative to the viewport observing them. That number might be increasing as the designer seems to like intersection animations.

Will that lead to performance issues? Is it better to have one IntersectionObserver that observes all elements or many IntersectionObservers that only observe one element?

Share Improve this question asked Apr 26, 2019 at 12:38 Sergio TxSergio Tx 3,8681 gold badge19 silver badges29 bronze badges 4
  • That is very hard to answer and guess and depends on a lot of factors like DOM size, how often these animations happen, how users use the site, what browsers you support and more factors. In general I would guess that for up to 10-20 elements adding individual observers is preferable to observing a shared root and over that it's better being with one although really - I wouldn't expect it to be a huge issue anyway regardless. – Benjamin Gruenbaum Commented Apr 26, 2019 at 12:47
  • 2 I can refer you to the code that does the actual work in Chromium, but I don't think that would help you answer your question - honestly it should be fast enough unless you're doing it to hundreds of elements at once. – Benjamin Gruenbaum Commented Apr 26, 2019 at 12:48
  • 3 See bennadel./blog/… - it says that one can be much faster. – krassowski Commented Mar 21, 2021 at 17:53
  • Thank you. I think we ended doing just that. It was 2 years ago :P – Sergio Tx Commented Aug 2, 2021 at 11:35
Add a ment  | 

1 Answer 1

Reset to default 4

As already stated, there are a lot of factors to consider!

I made the below library specifically for a media heavy site. A normal user session might setup and teardown > 1000 observers.

Since everything happens off the main thread it is hard to observer memory usage as show here. However, metrics showed us one IntersectionObserver for all the elements gave users an overall improvement. This package should be relatively easy to use!

https://github./snewer/intersection-observer-admin

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论