gpt4 book ai didi

附加到dom时的javascript执行顺序

转载 作者:行者123 更新时间:2023-11-29 18:08:04 25 4
gpt4 key购买 nike

所以我发现这个链接很好地解释了脚本是如何加载的:​​

http://www.html5rocks.com/en/tutorials/speed/script-loading/

但是我无法理解如果我这样做会发生什么:

<script>
var script = document.createElement("script");
script.src = "//www.domain.com/script.js";
document.getElementsByTagName("head")[0].appendChild(script);
</script>

<script>
console.log(myVar);
</script>

script.js 包含例如

var myVar = 'foobar';

所以我的问题是...因为 script.js 附加在一个单独的脚本标签中,这是否保证 script.js 将在之前加载和执行console.log()

最佳答案

来自您链接的网站:

Scripts that are dynamically created and added to the document are async by default, they don’t block rendering and execute as soon as they download, meaning they could come out in the wrong order. (emphasis theirs).

这意味着不能保证通过 JavaScript 添加到页面的脚本的执行顺序(如上例所示)。

如果您希望执行具有确定性,则需要手动禁用 async 属性:

var script = document.createElement("script");  
script.src = "//www.example.com/script.js";
script.async = false; // overwrite the default
document.getElementsByTagName("head")[0].appendChild(script);

关于附加到dom时的javascript执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29858980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com