What damage is done by document.write()? [duplicate]
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 开发者_StackOverflowthe 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.
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.
I just wanted to add a fiddle to to show a live example of what Andy E meant.
Basically the paragraph element won't be visible anymore because document.write()
overwrote it.
This snippet will prove it:
window.onload = function () {
document.write("Because I will overwrite everything.");
}
<p>Hello, I won't render anymore.</p>
精彩评论