What damage is done by document.write()? [duplicate]

Use of document.write() will break a web page - destroying and overwriting the entire DOM - if it's called after the document has finished being parsed. This is considered a poor use of document.write() and is/was the reason for criticism of a lot of older scripts.

window.onload = function ()
{
    document.write("Oops!");
}

Generally though, it's acceptable and rather widely used at parse-time to add something dynamically to the page in a synchronous manner:

<div>
  <script type="text/javascript">
  document.write("Well I'll be, your browser supports JavaScript!");
  </script>
</div>

It's mostly used by ad publishing services for adding the advertisements to a page, some Google APIs also use it.


Page blocking, that's enough or a reason when it's used improperly.

When you do document.write, as Andy said, it's synchronous meaning you have to wait on it before continuing with the rest of the page.

I don't want your site to hang up just because your ad server is down. Unfortunately, this is the case with SO, the ADs on the right use document.write using a script from another server that, if down, blocks the page from loading until it times out. This delay, because of document.write and a slow (often third party) ad server is far too often the reason a site is slow to load.

Side rant: Advertisements gets you money from views, ok good, you need to make a living. But don't be dependent on them from a technical perspective, as in their server is down, your site is FUBAR...do ads in a non-blocking way, there are many ways besides document.write to achieve this.