javascript - 使用 iframe 时是否有脚本执行顺序的规范?

标签 javascript html iframe

众所周知,浏览器将执行 <script>元素在页面源代码中呈现的顺序(除非 deferasync 等)。我无法确定的是,是否有保证订单跨越 <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 the script will be executed as soon as it is available, but without blocking further parsing of the page. 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.

(强调已添加。)

你问:

Say a.js takes a long time to load - it's guaranteed to still run before c.js. But what if inner.html and all it's resources (including b.js) have loaded before a.js - is there anything in the HTML spec that says b.js will not run before a.js?

是的,我上面引用的部分暗示 b.js 不会在 a.js 之前运行。根据规范,在获取和执行 a.js 时,解析将停止iframe 的处理直到解析 resume 之后才会发生,这意味着 b.js 不能在 a.js 之前运行。

c.js 可以在 b.js 之前执行。不过,我无法指出任何一个简洁的段落来证明这一点。对此的解释遍布整个规范。 iframe 触发导航到 src 中传递的 URL。 (在规范中,这表示为“将元素的子浏览上下文导航到 url”。导航描述为 here。)此导航事件将导致获取发生。 (获取描述为 here。)默认情况下,获取是并行执行的。带有 srcscript 元素也会获取一些数据,但是(没有 asyncdefer)它 在获取发生时停止解析。

关于javascript - 使用 iframe 时是否有脚本执行顺序的规范?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30186925/

相关文章:

javascript - 将数组显示为平均堆栈中的图像(节点+ Angular 等..)

html - IE7 CSS 不一致

javascript - Html/Js 输入范围对象动态加载到 div 中不起作用

JavaScript 删除事件

javascript - 谷歌地图需要很长时间才能加载

html - Bootstrap - 一行一行地超出它一点

javascript - 提交时的 JQuery 内容可编辑 div 和文本框不发送 POST

html - YouTube嵌入视频具有巨大的黑色边框

Javascript如何在用户放大时将叠加层居中

jquery - 如何在 jQuery UI 对话框中显示 IFRAME