|
阅读:7138回复:1
js中关于document.write的剖析
document.write() 其它并不那么简单。下面我们就来了解一下它。
Document.write() 方法将一个文本字符串写入一个由 document.open() 打开的文档流(document stream)。注:document.write写入的是由document.open打开的文档流。 因为 document.write 需要向文档流中写入内容,所以,若在一个已关闭(例如,已完成加载)的文档上调用 document.write,就会自动调用 document.open,这将清空该文档的内容。 大家,注意上面这句话:"若在一个已关闭的文档上调用 document.write,就会自动调用 document.open,这将清空该文档的内容". 这句话,解释了,我们在某些时候使用document.write()写入数据时,会将原来的内容清空。 示例说明: 1. 如果 document.write() 调用发生在 HTML 里的 <script> 标签中,那么它将不会自动调用 document.open()。则不会清空原来的内容 详见如下例子: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
document.write("hello world");
</script>
</head>
<body>
<p>这是一个段落</p>
</body>
</html>script标签写在html下面,效果一样,也不会清空原来的内容<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>这是一个段落</p>
<script type="text/javascript">
document.write("hello world");
</script>
</body>
</html>2. 向一个已经加载,并且没有调用过 document.open() 的文档写入数据时,会自动调用 document.open。会发现原来的内容会被清空 代码如下: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
function test(){
document.write("hello write");
}
</script>
</head>
<body onload="test()">
<p>这是一个段落</p>
</body>
</html>还有:一旦完成了数据写入,建议调用 document.close(),以告诉浏览器当前页面已经加载完毕。写入的数据会被解析到文档结构模型(DOM)里。 代码如下: function test(){
document.open();
document.write("hello write");
document.close();
}注意:document.write 和 document.writeln 在 XHTML 文档中不可用(控制台上会显示 "Operation is not supported"[NS_ERROR_DOM_NOT_SUPPORTED_ERR] 的报错信息)。 当打开本地的 .xhtml 格式的文件或任何其他 MIME 类型为 application/xhtml+xml 的文档时,均会报错。更多信息可查看 W3C XHTML FAQ。 注意:在有deferred 或 asynchronous 属性的 script 中,document.write 会被忽略,控制台会显示 "A call to document.write() from an asynchronously-loaded external script was ignored" 的报错信息。 注意:在 Edge 中,在 <iframe> 内部调用 document.write 多于一次时会引发错误 SCRIPT70: Permission denied。 注意:从 Chrome 55 开始,Chrome(可能)不会运行通过 document.write() 注入的<script>,以防止使用 2G 连接的用户找不到 HTTP 缓存。前往此链接查看这种情况发生需要满足的条件。 参考官方文档: https://developer.mozilla.org/zh-CN/docs/Web/API/Document/write |
|
|