Hacker News new | ask | show | jobs
by mcmatterson 2832 days ago
For someone who doesn’t follow lower level browser dev that closely, this seems like an optimization pretty specifically for a react style ‘nested redraws’ use case. Is this at all correct?
2 comments

Basically "<ul id='foo'><li>...</li></ul>" && #foo.append( ...li... ) may cause a redraw, recalc, reflow, of layout + styles for each LI you add to the UL, as well as the rest of the dom containing the UL.

However if you can do: "BEGIN TRANSACTION; ...#foo.append(...)...; END TRANSACTION;" it gives you a mechanism to "freeze" all or some of the display (think of it as a subset double-buffer), and "blit" the changed dom to the UI when you're done (with the possibility of: " && CONTINUE TRANSACTION".

Imagine a simple list of search results with alternating row colors (white / grey backgrounds) specified by css (nth-child %2 == 0).

If you prepend elements, instead of appending elements it might cause all elements to change color and re-render, on each insertion.

If you append elements instead then it's likely a more efficient on an individual element basis than prepending, but if you had the ability to "lock" the affected display area until you're done with your for-loop, then the browser can avoid updating the area at all until the "COMMIT" call (multiple actions, with a single commit resolution at the end).

Think of it as "batch these dom updates..." Git/SVN multi-file commits vs CVS commits (single-file).

For many such cases, i.e. layout changes triggering the recalculation of siblings or ancestors, contain[0] might be a more lightweight alternative.

[0] https://developer.mozilla.org/en-US/docs/Web/CSS/contain

Isn't that what document fragments are for? If your changes are all one tree you can build it then insert it all, right?

(Or set inner html? :-)

I would actually say that non-React-style code would benefit even more. Suppose the user clicked a different sort tab on a table, and the code is busily removing and re-inserting elements in the dom, which the browser attempts to layout and display at the same time, leading to a lot of wasted calculations and visible "jank".