gpt4 book ai didi

javascript - 具有 asyc 属性的脚本仍然会阻止其他脚本执行

转载 作者:行者123 更新时间:2023-12-02 18:12:32 26 4
gpt4 key购买 nike

注意:我没有开发这个网站 - 我只是需要处理它。

我有一个包含 LAB.js 的文档,用于在头部异步加载一系列脚本。再往下,我还有两个外部脚本,一个在头部的下方,另一个在 body 的顶部。

这两个脚本通常无法访问。它们都被标记为“异步”,并且不会阻止文档加载。然而 - 它们显然阻止了其他脚本的执行。

需要明确的是,第一系列脚本会立即下载,但在下载其他两个异步脚本之前似乎不会执行。

该网站不是公开的,并且无法在 jsfiddle 中创建此类问题。粗略的说明:

<!doctype html>
<head>
<!-- This script asynchronously loads many others -->
<script src="/js/LAB.js"></script>

<script src="slow-server/js/slowscript1.js" async></script>
</head>
<body>
<script src="show-server/js/slowscript2.js" async></script>
</body>

Lab.js 信息:http://labjs.com/

LAB 会将其他几个脚本标记添加到要异步加载的头部。它们都会立即下载,但在“慢速服务器”脚本响应之前不会执行。有时需要一段时间。在我看来,对于具有 async 属性的脚本来说,这似乎是不正确的行为(我正在 Chrome 中进行测试)。我有什么遗漏的吗?

最佳答案

来自this MDN page :

There are three possible modes that can be selected using these attributes. If the async attribute is present, then the script will be executed asynchronously, as soon as it is available. If the async attribute is not present but the defer attribute is present, then the script is executed when the page has finished parsing. If neither attribute is present, then the script is fetched and executed immediately, before the user agent continues parsing the page.

因此,当脚本异步时,它将立即从服务器获取,但 DOM 解析将并行继续。这部分简单明了。

然后,一旦异步脚本被获取,它将被执行。此执行可能在 DOM 完成加载之前或之后,完全取决于加载/解析的时间,并且可能在页面中的其他非异步脚本运行之前或之后。

请注意,由于浏览器中的 JavaScript 是单线程的,一旦此异步脚本开始执行,在该脚本完成之前不会运行其他脚本,即使它是“异步”的。脚本上的异步允许继续解析 DOM(而不是阻止),但它不会阻止脚本在可用时执行,并且一旦执行,其他处理必须等待它完成执行。

如果您希望脚本在 DOM 和 DOM 中的任何常规脚本加载并运行之后才执行,那么您应该使用“defer”,而不是“async”。

仅供引用,如果您想了解所有这些的实际规范,那就是 here .

<小时/>

如果您想更详细地解释所有这些如何适用于您的具体情况,您至少必须向我们提供您所询问的脚本的伪代码表示,因为您的文字不够清楚关注。

关于javascript - 具有 asyc 属性的脚本仍然会阻止其他脚本执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19598002/

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