Reputation: 593
It seems that ResizeObserver
is best used when you have one instance managing the behaviors of many elements (as pointed out in one of the sources from "ResizeObserver one vs multiple performance"):
Observe size of 126 divs during a 2 second animation of width/height.
All elements are observed by a single ResizeObserver.
Total observer time: 69ms
Each element is observed by separate ResizeObserver.
Total observer time: 585ms
However, as far as I can tell you can only really specify a single behavior for an instance of ResizeObserver
, which then gets run for any elements that it's observing. How should I observe multiple elements with different behaviors? From what I can see, I can either:
ResizeObserver
and figure out at runtime what behavior should be used for a given element (which seems needlessly complex, and I don't know how reliable comparing element references would be in production), orResizeObserver
, which would make behavior simpler but theoretically reduce performance.Alternatively, are the performance losses for using multiple instances of ResizeObserver
even something that I should be worried about at a small to medium scale?
Upvotes: 2
Views: 1643
Reputation: 27295
…figure out at runtime what behavior should be used for a given element (which seems needlessly complex, and I don't know how reliable comparing element references would be in production)…
I don't think this needs to be particularly complicated.
You could have a collection of behaviors, each with a predicate
function and a handler
function. The predicate determines whether it's applicable to the given element, and the handler performs the behavior. (This might not be super performant if you've got thousands of behaviors, but I'm assuming you don't.)
Something along these lines?
const behaviors = [
{
predicate: element => element.classList.contains('first'),
handler: element => {
// do stuff
}
},
{
predicate: element => element.classList.contains('second'),
handler: element => {
// do other stuff
}
},
];
const observer = new ResizeObserver((entries) => {
for (let entry of entries) {
// for single behavior
behaviors.find(b => b.predicate(entry))?.handler(entry);
// or every applicable behavior
behaviors
.filter(b => b.predicate(entry))
.forEach(b => b.handler(entry);
}
})
Upvotes: 1