What damage is done by [removed]()? [duplicate]

2020-01-27 07:50发布

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条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-01-27 08:17

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.

查看更多
▲ chillily
3楼-- · 2020-01-27 08:20

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.

查看更多
霸刀☆藐视天下
4楼-- · 2020-01-27 08:24

This snippet will prove it:

window.onload = function () {
  document.write("Because I will overwrite everything.");
}
<p>Hello, I won't render anymore.</p>

查看更多
做个烂人
5楼-- · 2020-01-27 08:33

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.

查看更多
登录 后发表回答