HTML 在 Internet Explorer 中导入加载顺序

HTML imports load order in Internet Explorer

我有一个呈现一些 Polymer 1.0 自定义元素的网页。 在我的 index.html 文件的 head 部分中,我有以下内容:

<link rel="import" href="my-elements.html">
<script src="script1.js"></script>
<script src="script2.js"></script>

my-elements.html 引用其他 HTML 文件(通过 HTML 导入),这些文件又使用标准 script 标签引用 javascript 文件。

使用 Chrome 浏览器,一切正常。 my-elements.html 中的 javascript 个文件在 script1.jsscript2.js 之前加载。然而,对于 Internet Explorer (v11),它们以相反的顺序加载。即 script1.jsscript2.js 首先加载。

在下面的文章中它指出 "HTML Imports block <script> elements. The <script> doesn’t run until its preceding imports are loaded":

https://gist.github.com/omo/9986103

为什么 Internet Explorer 的顺序不同?

请注意,我使用 webcomponents-lite.js 作为我的 web 组件 polyfill 库。我怀疑我遇到的行为是由于 Internet Explorer 没有对 HTML 导入的本机支持,但想知道如何解决这个问题,以便脚本按预期顺序加载。

你说得对,是因为 IE 使用了 polyfill,所以 <link> 标签没有按顺序进行。

解决方法是在加载 HTML 导入时监听 webcomponents-lite.js 库触发的 HTMLImportsLoaded 事件。

<link rel="import" href="my-elements.html">
<script>
  document.addEventListener( "HTMLImportsLoaded", function () {
    var s1 = document.createElement( "script" )
    var s2 = document.createElement( "script" )
    s1.setAttribute( "src", "script1.js" )
    s2.setAttribute( "src", "script2.js" )
    document.head.appendChild( s1 )
    document.head.appendChild( s2 )
  } )
</script>