Javascript inside HTML import not affecting imported HTML

154 views Asked by At

I am importing an html document, form.html, from a script located in my index.html file.

form.html is a basically a fragment of HTML and at the bottom of the html is an internal script that attaches the html to the main document:

Afterwards, I reference an external script that is supposed to do some stuff to the HTML in form.html. However, this fails to have an affect in Firefox.

If I inspect the <head> of the main document in Firefox developer tools, I can see the "document fragment" composed and with the correct scripting affect. However, the actual imported HTML that appears in the body is unaffected.

I have tried inlining the script at the bottom of form.html. I also tried using window.onload to attach the external script to the end of the body of the main document as well as trying to use a link tag as per this question.

Not quite sure what else to try. I would like to keep the script modular and contained inside form.html if possible as to only request it when that HTML page is requested.

Thanks,

1

There are 1 answers

0
Supersharp On BEST ANSWER

When using the HTML Imports polyfill, the processing of the imported document is only asynchronous. So you should wait for the HTMLImportsLoaded event or use the HTMLImports.whenReady() method to be sure the content was imported.

<head>
    <script src="html-imports.min.js"></script>
    <link rel="import" src="from.html">
<body>
    //code to be injected
    <script>
        document.addEventListener( 'HTMLImportsLoaded' , ev => {
            //you can safely access the imported code in the body
        } )
    </script>