众所周知,浏览器将执行 <script>
元素在页面源代码中呈现的顺序(除非 defer
和 async
等)。我无法确定的是,是否有保证订单跨越 <iframe>
的规范元素也。
如果我的主页包含:
<html>
<head>
<script src="a.js"></script>
</head>
<body>
<iframe src="inner.html" />
<!-- ... -->
</body>
</html>
inner.html 是:
<html>
<head>
<script src="b.js"></script>
</head>
<body>
<!-- ... -->
</body>
</html>
是否在规范中定义 a.js
将在 b.js
之前执行?
如果主页看起来像这样怎么办:
<html>
<head>
<script src="a.js"></script>
</head>
<body>
<iframe src="inner.html" />
<!-- ... -->
<script src="c.js"></script>
</body>
</html>
这里保证的执行顺序是什么,如果有的话?说 a.js
需要很长时间才能加载 - 它保证在 c.js
之前仍然运行.但是如果inner.html
怎么办?并且它的所有资源(包括 b.js
)都在 a.js
之前加载- HTML 规范中是否有任何内容表明 b.js
不会在 a.js
之前运行?如果它都能及时正常加载,是否在规范中定义了是否b.js
应该在 c.js
之前或之后执行?
到目前为止,我从 the <iframe>
spec 中找到的最好的是:
When a Document in an iframe is marked as completely loaded, the user agent must run the iframe load event steps in parallel.
然而,这似乎只是说(当您深入研究“iframe 加载事件步骤”时)load
事件将在主页上运行的其他内容中调度,但没有说明何时解析内页和加载内容以及(关键)何时在其中运行脚本。
最佳答案
specification script
元素对我来说似乎很清楚:
There are three possible modes that can be selected using these attributes. If the
async
attribute is present, then thescript
will be executed as soon as it is available, but without blocking further parsing of the page. If theasync
attribute is not present but thedefer
attribute is present, then thescript
is executed when the page has finished parsing. If neither attribute is present, then thescript
is fetched and executed immediately, before the user agent continues parsing the page.
(强调已添加。)
你问:
Say
a.js
takes a long time to load - it's guaranteed to still run beforec.js
. But what ifinner.html
and all it's resources (includingb.js
) have loaded beforea.js
- is there anything in the HTML spec that saysb.js
will not run beforea.js
?
是的,我上面引用的部分暗示 b.js
不会在 a.js
之前运行。根据规范,在获取和执行 a.js
时,解析将停止。 iframe
的处理直到解析 resume 之后才会发生,这意味着 b.js
不能在 a.js
之前运行。
c.js
可以在 b.js
之前执行。不过,我无法指出任何一个简洁的段落来证明这一点。对此的解释遍布整个规范。 iframe
触发导航到 src
中传递的 URL。 (在规范中,这表示为“将元素的子浏览上下文导航到 url
”。导航描述为 here。)此导航事件将导致获取发生。 (获取描述为 here。)默认情况下,获取是并行执行的。带有 src
的 script
元素也会获取一些数据,但是(没有 async
或 defer
)它也 在获取发生时停止解析。
关于javascript - 使用 iframe 时是否有脚本执行顺序的规范?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30186925/