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.

Leave a Comment