-->

HTML imports load order in Internet Explorer

2019-06-28 03:15发布

问题:

I have a web page that renders some Polymer 1.0 custom elements. In the head section of my index.html file I have the following:

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

my-elements.html references other HTML files (via HTML imports) which in turn references javascript files using standard script tags.

With Chrome browser it all works as expected. The javascript files within my-elements.html load before script1.js and script2.js. However with Internet Explorer (v11) they load in the opposite order. i.e. script1.js and script2.js load first.

In the following article it states "HTML Imports block <script> elements. The <script> doesn’t run until its preceding imports are loaded":

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

So why is the ordering different with Internet Explorer?

Note that I'm using webcomponents-lite.js as my web components polyfill library. I suspect the behaviour I'm encountering is due to Internet Explorer not having native support for HTML imports, but would like to know how to work around this so that the scripts load in the intended order.

回答1:

You're right, it's because IE is using a polyfill, so the <link> tag is no proceeded sequentially.

The workaround is to listen to the HTMLImportsLoaded event fired by the webcomponents-lite.js library when the HTML Import is loaded.

<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>