resize-observer icon indicating copy to clipboard operation
resize-observer copied to clipboard

[Performance] Reduce calls to getBoundingClientRect()

Open devrelm opened this issue 9 years ago • 3 comments

In some browsers, getBoundingClientRect() forces a new layout calculation on each call.

Currently, the resize-observer module calls getBoundingClientRect() multiple times during each animation frame, especially when the size has changed. We should instead cache this value the first time that it is called per animation frame and reuse that value.

devrelm avatar Jun 14 '16 11:06 devrelm

A quick and obvious win is to at least group capturing of width and height.

https://github.com/pelotoncycle/resize-observer/blob/master/resize-observer.js#L131-L132

This causes two layout calculations.

gajus avatar Sep 07 '16 12:09 gajus

You could further reduce the number of getBoundingClientRect calls by using MutationObserver: setup an observer on all parent elements. In combination with window "resize" event, this will give an indication when dimensions of the element could have changed. This approach is not bulletproof (e.g. CSS transitions), but it would cover 99% of use cases.

gajus avatar Sep 07 '16 12:09 gajus

Hi! I'd like to mention that it'd better to avoid gbcr at all as its data is affected by paddings, borders, scrollbars and CSS transformations, while width and height properties of a content rectangle represent content width and content height respectively. And while using it you need to check whether an element being observed is not an inline element.

Probably, the best thing to do would be to use either computed styles of width and height or clientWidth and clientHeight properties of an element. But the first approach gives incorrect results for an element whose box model is the border-box. And with client width/height you would only need to subtract paddings.

que-etc avatar Sep 13 '16 11:09 que-etc