- From: Tristan Fraipont <notifications@github.com>
- Date: Wed, 16 Oct 2024 00:42:40 -0700
- To: whatwg/dom <dom@noreply.github.com>
- Cc: Subscribed <subscribed@noreply.github.com>
- Message-ID: <whatwg/dom/issues/1318/2415974941@github.com>
Most browsers (all?) already do "store" the full computed box values and only recompute it when the layout has been "dirtied". So doing something like ```js for (const elem of elems) { const rect = elem.getBoundingClientRect(); // do something with rect } ``` is not in itself "bad". What's bad is when in the `// do something` the layout is dirtied. As long as nothing modifies the DOM or CSSOM in that loop, a single reflow will happen. So this could actually be done in user-land by running a first loop that will gather all the needed values, and a second loop that will use these gathered values. This obviously is fragile as it requires no other code did dirty the layout before you gathered the values, but while having an out-of-date state accessible might be useful in some (rare?) cases, a lot of APIs and properties do need an up-to-date box-model and thus trigger reflows. I don't think a single property can hold all of these (e.g. how would you call `document.getElementFromPoint()` from your design?), and some like `scrollTo()` will anyway trigger a reflow because they both read the computed scroll value synchronously and dirty it right away... Unfortunately there are [so many different things](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) that do trigger a reflow that a catch-all solution seems almost impossible. #270 could offer a nice path toward separating better DOM changes and reading, but that would certainly not solve the whole problem either. Personally, to cope with this issue I use a strategy which registers a couple of callbacks: one getting the computed values after a `ResizeObserver` callback (and thus after the browser's own layout recalc), and another that will dirty the box-model after all the other "reading callbacks" have been executed. But for it to work, all the code that does read the layout has to go through this strategy (i.e. most libraries might just break the model), and we have to be sure that nothing will read the layout again in the "dirty" callbacks, which is not easy at all, e.g. did you know that `canvas2DContext.fillText()` does need a reflow? And then once again some methods like `scrollTo()` are just evil here. -- Reply to this email directly or view it on GitHub: https://github.com/whatwg/dom/issues/1318#issuecomment-2415974941 You are receiving this because you are subscribed to this thread. Message ID: <whatwg/dom/issues/1318/2415974941@github.com>
Received on Wednesday, 16 October 2024 07:42:44 UTC