javascript - 为什么在结束上下文之前评估动态内联脚本标记?

标签 javascript html

有人可以指出有关此行为的相关标准部分吗?

http://arcanis.github.io/dynamic-scripts/

基本上,有两件事让我感到惊讶:我一直认为动态脚本标签总是在从第一个执行程序返回后立即加载(就好像浏览器正在执行内部 setImmediate)。然而,在这个例子中:

  • 内联标签在窗口范围内立即执行(它们不等待当前执行流结束)

  • 远程标签在每个其他标签之后执行,即使它们已附加在它们之前也是如此

这种行为是否正确? Chrome、Firefox 甚至 IE11 得到相同的结果(除了 IE 没有触发动态附加的远程脚本),所以我可能遗漏了一些东西。


供引用的短代码示例:

<script>
    log("Starting standard script tag ...");
    var s = document.createElement( 'script' );
    s.appendChild( document.createTextNode( 'log("Executing dynamically appended inline script tag")' ) );
    document.querySelector( 'head' ).appendChild( s );
    log("Ending standard script tag");
</script>

最佳答案

首先我需要说明一下,我没有时间仔细查看规范,所以我可能理解有误。

但是看部分prepare a script 你有以下陈述:

[...]
15. Then, the first of the following options that describes the situation must be followed:
[...]
If the element does not have a src attribute, and the element has been flagged as "parser-inserted", and either the parser that created the script is an XML parser or it's an HTML parser whose script nesting level is not greater than one, and the Document of the HTML parser or XML parser that created the script element has a style sheet that is blocking scripts
The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

Set the element's "ready to be parser-executed" flag. The parser will handle executing the script.
[...]
Otherwise
The user agent must immediately execute the script block, even if other scripts are already executing.

我是这样理解的:

  • 以编程方式创建的元素匹配Otherwise条件,因为其他条件(包括我省略的条件)不会匹配,因此必须立即执行脚本。

但正如我所说,我没有时间详细阅读整篇文章,我会在接下来的几天阅读。但就目前而言,这可能已经对您有所帮助。

编辑 在我第二次阅读第一个引用的条件后,我意识到我确实没有仔细阅读它([...]and the Document of the HTML parser or XML parser that created the script element has a style sheet that is blocking scripts[...]),所以我用<del>标记了.

关于javascript - 为什么在结束上下文之前评估动态内联脚本标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22808980/

相关文章:

javascript - 我想在我的可移动 div 内创建一个像窗口一样的 div

javascript - 如何使用 JavaScript 或 jQuery 将选定的文本包装到特定标签中的网页中?

html - 为什么我的动画元素不居中?

javascript - 如何根据条件使用 Angular 检测输入类型

javascript - 简单的Javascript游戏,重复功能。 (新手问题)

javascript - 如何在选择列表中显示扩展选项?

javascript - jQuery querySelectorAll 不起作用?

javascript - CSS、JavaScript、HTML - 所见即所得编辑器中的空段落和错误代码

javascript - 单击时获取元素的 id ( php, jquery, ajax, javascript )

javascript - 在 Google Analytics 中,为什么事件标签=(未设置)