问题描述
拥有以下代码:
<html>
<head>
<script>
function elem_onload() {
console.log("elem_onload");
};
</script>
</head>
<body onload="elem_onload()">
<script type="text/javascript" src="script.js" defer></script>
</body>
</html>
script.js:
script.js:
console.log("external script");
defer属性似乎不起作用。输出为:
the defer attribute doesn't seems to work. The output is:
external script
elem_onload
是否带有延迟属性。不应该
whether with or without defer attribute. Shoudn't it be
elem_onload
external script
是否定义了延期?
我想说明我的回答并不重复
I'd like to state that my answer isn't duplicate of
引用的推荐答案是内联脚本,浏览器行为对我来说很明显 - 它只是忽略 defer
。我的问题是关于外部脚本,在这种情况下,浏览器应该在解析文档后执行外部延迟脚本
The referenced recommended answer is about inline script where the browser behavior is clear for me - it simply ignores defer
. My question is about external script in which case the browser should execute the external deferred script
因为文件因此在 onload
事件后出现。
as documentation states hence after onload
event.
所以我在等待一个合适的答案...
推荐答案
外部在 defer 属性延迟的脚本触发rel =nofollow> DOMContentLoaded
),即初始HTML文档已完全加载并解析。另一方面,< body>
标记上的 onLoad
属性仅在网页完全启动时触发已加载。
The external script deferred by the defer
attribute is executed before the (DOMContentLoaded
) is fired, i.e. when the initial HTML document has been completely loaded and parsed. The onLoad
attribute on a <body>
tag, on the other hand, fires only when a web page is fully loaded.
因此,defer属性确实有效。您可以通过尝试以下两种情况来测试它。在这两种情况下, script.js 文件的内容应为:
Therefore, the defer attribute is indeed working. You may test it by trying the two cases below. In both cases the content of script.js file should be this:
console.log(document.getElementById('sample').innerHTML);
CASE 1 HTML - defer
- > logs示例文本
CASE 1 HTML - with defer
--> logs "Sample text"
<body onLoad="elem_onload()">
<script type="text/javascript" src="script.js" defer></script>
<div id="sample">Sample text</div>
</body>
案例2 HTML - 没有延期
- >记录错误
CASE 2 HTML - without defer
--> logs an error
<body onLoad="elem_onload()">
<script type="text/javascript" src="script.js"></script>
<div id="sample">Sample text</div>
</body>
这篇关于延迟属性和onload事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!