0

I'm trying to understand, why HTML5 Import doesn't work with dynamically created link element.

First example. It's work fine.

main_page.html:

<head>
    <link rel="import" href="import.html">
</head>
<body>
    <script>
        var imported = document.querySelector('link[rel="import"]').import;
        var el = imported.querySelector('#foo');
        document.body.appendChild(el);
    </script>
</body>

import.html:

<div id="foo">foo</div>

Second example. For some reason, it doesn't work.

main_page.html:

<body>
    <script>
        var link = document.createElement('link');
        link.rel = 'import';
        link.href = 'import.html';
        document.head.appendChild(link);

        var imported = document.querySelector('link[rel="import"]').import;
        var el = imported.querySelector('#foo');
        document.body.appendChild(el);
    </script>
</body>

import.html:

<div id="foo">foo</div>

Why it occurs and how it may be fixed?

john c. j.
  • 725
  • 5
  • 28
  • 81

1 Answers1

1

That would happen because the link is not yet loaded when you are calling querySelector('link[rel="import"]').

One way to fix it would be to run the subsequent code when the link is loaded using link.onload. You can even save that querySelector call, which should make it a bit faster:

 var loadFoo = function(event) {
   var imported = event.target.import;
   var el = imported.querySelector('#foo');
   document.body.appendChild(el);
 }

 var link = document.createElement('link');
 link.rel = 'import';
 link.href = 'import.html';
 link.onload = loadFoo;
 document.head.appendChild(link);

You could (and probably should) add an onerror handler to run when things go wrong.

helb
  • 3,154
  • 15
  • 21
  • Thank you :-) It works. Could you elaborate, what are another ways to fix it? I'm asking just out of curiosity, for my further self-education. – john c. j. Feb 24 '17 at 10:09
  • ES6 Promises. But it seems like overkill for a single link. See this: https://developers.google.com/web/fundamentals/getting-started/primers/promises (it's about images, but link works more or less the same way). – helb Feb 24 '17 at 10:14