Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One intersectionObserver to observe many elements or one intersectionObserver per 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?

like image 414
Sergio Tx Avatar asked Apr 26 '19 12:04

Sergio Tx


People also ask

Can intersection observer observe multiple elements?

observe() The IntersectionObserver method observe() adds an element to the set of target elements being watched by the IntersectionObserver . One observer has one set of thresholds and one root, but can watch multiple target elements for visibility changes in keeping with those.

What is intersection observer used for?

The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport.

What is rootMargin?

Experimental: This is an experimental technology. Check the Browser compatibility table carefully before using this in production. The IntersectionObserver interface's read-only rootMargin property is a string with syntax similar to that of the CSS margin property.


1 Answers

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.com/snewcomer/intersection-observer-admin

like image 122
snewcomer Avatar answered Oct 05 '22 11:10

snewcomer