HTML5 Import with dynamically created link

886 Views Asked by At

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?

1

There are 1 best solutions below

2
On BEST ANSWER

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.