The “Live DOM” Is Not “Slow”, “Bad”, Or “Wrong”. Web Developers Are.
From various sources — front end framework fanboys in particular — you’ll hear a lot of nonsense about how modifying the live DOM is “bad” or magically “slow”. Oh you need to batch your changes, oh you need to use a document fragment or the shadow DOM instead, blah blah blah blah…
And to be brutally frank, 99% of the time people say this stuff they’re flapping their arse-cheeks in the wind.
The only time this might make sense — using innerHTML — isn’t even true. And you know what? Just stop using that outdated, insecure, train wreck laundry list of how NOT to add stuff to a page… Or at least, how not to do so in all but a few corner-cases where speed doesn’t matter and you know the content is safe.
There are a number of legitimate reasons to use document fragments, but things like the “shadow DOM” seem to be a waste of time and code if you understand how browsers work and know one simple, little, tiny detail. A detail that reveals many claims and ideas to be utter nonsense.
DOM changes in the browser do not render until scripting execution is released!
Nothing, nada, zip, zilch, nein! Until scripting execution stops, then hands control back to the browser, your DOM changes don’t do anything in terms of triggering re-application of CSS or rendering. Why is that so important a detail?
Have you heard people saying that you should “batch your DOM changes”? Or “don’t write to the DOM because you don’t want the render to happen yet”? How about “making all the changes last makes if faster”?
BULLCOOKIES! Every last such claim is utter and complete nonsense. Because again:
Browsers do not render scripted DOM changes until after scripting execution releases control!
Let’s Prove It!
The easiest way I can think of is to simply spew up a bunch of new paragraphs filled with lorem-ipsum text in sufficient number (32,768 should suffice) we can get a meaningful performance.now() of the start, after DOM writing is complete, and then after the render is complete. Small, simple, easy to track.