Document.write

https://news.ycombinator.com/rss Hits: 1
Summary

This is really cool: ...blah... <script>writeImage("dog.jpg", "my dog")</script> ... blah blah... Under the hood it works like this: function writeImage(url, title) { document.write(` <img src="${url}"><div class="caption">${title}</div> `); } And leads to: ...blah... <img src="dog.jpg"><div class="caption">My dog</div> ...blah blah... 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 The same approach works for reusing chunks of HTML between pages: <script src="common.js"></script> <script>writeMetaViewport()</script> ...page content... when in common.js you have something like this: function writeMetaViewport() { document.write(` <meta name="viewport" content="width=1000px, maximum-scale=1"> `); } Now can make a site with reusable pieces and it'll work purely on static hosting, no site generator, no server-side code, development workflow is Ctrl+S and reload. Amazingness. But this function was known forever and all the wizards say it's dangerous... why? Why indeed? Well, it's true that it was used badly. I'll go ahead and propose two rules to use document.write() safely and well: Rule 1. Only call it at the document toplevel, or in functions whose name begins with "write". Apply the same rule recursively to functions that begin with "write". Rule 2. Never use document.write() to output <script> or <style> tags. The first rule is easy to explain. If you call document.write() after the page is loaded, it'll delete the whole page. Yes really. So it's worth separating all functions into those that can write, and those that can't. It's easily checkable. For the second rule we go into a bit more detail. What happens if you output a <script>? It's the same as a blocking web request. If there's two of them on the page, they'll happen sequentially. Since <style> blocks subsequent <script>'s from executing until it's loaded, ...

First seen: 2025-08-16 10:26

Last seen: 2025-08-16 10:26