Document.write
8 comments
·August 14, 2025diggan
cousin_it
Yeah. At the end of the post I mention another method (document.currentScript) which allows you to do many of the same things, with no risk of messing up the parser. Realized it only after writing the post and talking a bunch of people about it :-)
null
Sjeiti
I also thought the writing/parsing makes it a lot slower than DOM createElement methods. Here's also an interesting SO thread: https://stackoverflow.com/questions/802854/why-is-document-w...
Cyykratahk
I'd always assumed the opposite, seeing as a browser's primary function is to parse HTML text into DOM nodes as efficiently as possible.
But on the other hand, since document.write (rightfully) gets such little usage - and has a multitude of footguns - I wouldn't be surprised if browsers used a different, slower code path when executing it; if only to prevent it from borking the parser.
miragecraft
I disagree that you shouldn’t use document.write for <script> and <style> tags, as it’s the only way to force dynamically inserted script to run in a parser-blocking manner during parsing, and to prevent flash of unstyled content (FOUC) for dynamically inserted styles.
Yes it’s slower, but does it matter for your specific use case? Async scripts are harder to reason about, esp if you have nested templates. FOUC is also a much bigger and more noticeable problem than the tiny delay to parse the CSS snippets.
Forcing scripts to be parser-blocking is also needed if you want to nest document.write, to ensure it is writing to the correct location in the document.
I created an HTML includes library that utilizes document.write extensively: https://miragecraft.com/projects/x-include
> Whoa, HTML templating? It inserts the stuff directly where the function is called, and it just works? And it's been available in browsers forever? Stop the presses, I gotta rewrite all my static sites
As someone who learned HTML, CSS and JS in the late 90s/early 2000s, we've finally come full circle :) Back in those days, `document.write` was commonly the first piece of JS many of us wrote, here is a `document.write` I wrote 14 years ago, seems to be the earliest one I could find in my public GitHub repos: https://github.com/victorb/Flashback-Citat/blob/f4da38ace620...
Most of us were told early to avoid `document.write` like the plague though, as there generally was better ways of achieving the same thing, but without all the drawbacks.