document.write() 造成了什么损害? [英] What damage is done by document.write()?

查看:23
本文介绍了document.write() 造成了什么损害?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在调用 document.write() 的那一刻发生了什么不好的事情?

我听说过关于 document.write 对 DOM 或 Javascript 库的使用产生不利影响的点点滴滴.我有一个问题摆在我面前,我怀疑它是相关的,但无法找到该方法造成的损害的简明摘要.

解决方案

使用 document.write() 会破坏网页 - 破坏和覆盖整个 DOM- 如果在文档解析完成后调用它.这被认为是对 document.write() 的不良使用,并且是/曾经是批评许多旧脚本的原因.

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

不过,一般来说,在解析时以同步方式动态地向页面添加内容是可以接受的并且相当广泛使用:

<script type="text/javascript">document.write("好吧,你的浏览器支持 JavaScript!");

它主要由广告发布服务用于向页面添加广告,一些 Google API 也使用它.

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.

解决方案

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.

这篇关于document.write() 造成了什么损害?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆