我有一大群网站在<head>
标记上有一个include(),这包括从包含javascript代码的文件加载内容,此代码使用document.write()。
浏览器上的代码如下所示:
<html>
<head>
<script>document.write('stuff');</script>
</head>
<body>
content
</body>
</html>
这似乎工作正常,但我想知道它是否可能在某些浏览器/计算机上失败,因为head标签位于body标签之前,而document.write写入body标签。当这个标签还没有被加载时,document.write是否可能会尝试写入body标签?
答案 0 :(得分:2)
head标签的document.write是否需要等待window.onload?
不,恰恰相反。
文档关闭时将触发load事件。您无法写入已关闭的文档,因此调用write
会隐式调用open
并删除现有文档。
这似乎工作正常,但我想知道它是否可能在某些浏览器/计算机上失败,因为head标签位于body标签之前,而document.write写入body标签。
write
将写入脚本元素,而不是正文。
但是,在这种情况下,您正在编写文本内容(不能将其显示为head元素的子节点)。
这将导致head元素结束(结束标记是可选的)和要开始的主体(开始标记是可选的)以及要在主体开头写入的内容。
</head>
<body>
将被视为无效的HTML,浏览器将尽一切努力从作者错误中恢复。
您可以在DOM检查器中查看结果:
答案 1 :(得分:1)
这是一个显示答案的小测试用例:
<html>
<head>
<script>
document.write('stuff');
console.log("document has written from head");</script>
</head>
<body>
<script>
window.onload = function() {
console.log("on load function has triggered");
}
</script>
</body>
</html>
Chrome Dev Tools控制台的输出:
document has written from head test.html:3
on load function has triggered test.html:8
所以是的,head部分中的代码将在onload函数之前运行。
请注意document.write()
不是您想要练习的内容。根据我的经验,我从来没有使用它。它会覆盖DOM,如果你不知道它是如何工作的话可能会很讨厌。你应该使用DOM。