gpt4 book ai didi

javascript - 动态添加 javascript 以立即执行

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

我正在使用 DOM 将脚本动态添加到页面。

  1. 如果我添加脚本文本(例如 script.text = "...";),它会立即运行。

  2. 但是,如果我添加一个外部脚本(例如 script.src = "...";),它将在我的脚本完成后运行。

所以在下面的例子中我会得到

"0 1 2"

"3 3 3"

分别。

( 1.js 包含相同的字符串 - "document.body.innerHTML += i" )

<body>
<script>
for (i = 0; i < 3; i++) {
var script = document.createElement('script');
script.src = "1.js";
// script.text = "document.body.innerHTML += i";
document.body.append(script);
};
</script>
</body>

我不明白为什么会这样,添加后如何立即运行1.js?

最佳答案

外部脚本的动态加载按照通过浏览器请求的顺序排队。这意味着它们不会在下载后立即执行。

W3 HTML5 规范 Scripting部分:

If the element has a src attribute, does not have an async attribute,and does not have the "force-async" flag set

The element must be added to the end of the list of scripts that will execute in order as soon as possible associated with the Document of the script element at the time the prepare a script algorithm started.

关于javascript - 动态添加 javascript 以立即执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45278502/

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