Hacker News new | ask | show | jobs
by ramses0 2837 days ago
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).

2 comments

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? :-)