views:

117

answers:

2

What bad things happen at the moment document.write() is invoked?

I've heard bits and pieces about document.write having an adverse impact on the DOM or on the use of Javascript libraries. I have an issue in front of me that I suspect is related, but have not been able to find a concise summary of what damage the method does.

+4  A: 

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.

Andy E
+2  A: 

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.

Nick Craver
Yeah I got fed up of the ads on here blocking the rest of the page, so I now have `127.0.0.1 ads.stackoverflow.com` in my hosts file
Andy Shellam
+1 for the side rant, `ads.stackoverflow.com` seems to have trouble on a regular basis (mostly mornings GMT). Not the best use of `document.write`. :-)
Andy E
I wrote a lib that allows you to load document.write scripts async: http://github.com/iamnoah/writeCapture
noah
@noah - Question though, if you're bringing in jQuery, why would you be using `document.write` at all?
Nick Craver
@Nick - writeCapture works with 3rd party scripts (Virtually every ad server out there uses document.write). Also, you don't have to use jQuery with writeCapture.
noah