javascripthtmlweb-componenthtml5-templatehtml-imports

HTML Imports not working... Even though it's supported


Im a little lost right now.. I'm trying out the web components spec with custom elements, templates, imports, etc. But for some reason the import spec just won't work! Chrome does not seem to load my import in the sources section even though its supported in my version (67), all the code is correct and so is the pathname. Could anyone help me out? Here's my project: Link to github project

If you open "index.html" you can see I have a link tag pointing to an html file. In that file I'm using a template tag and appending its content to the shadowDOM of a custom element I created. It works if I manually copy and paste the code into the body of the main html file, but doesn't load when I try to import it. Any input would be greatly appreciated, thanks!


Solution

  • The <template> element is not in the main document but in the imported document. Therefore, you won't be able to get it using document.getElementById.

    Instead you should search it in the imported document:

    1° In the <script> of the import, define a variable with a reference to the imported document:

    var importedDoc = document.currentScript.ownerDocument
    

    2° In the custom element class definition, use it to get the <template>.

    constructor() {
        super()
        let template = importedDoc.getElementById( 'social-button' )
        ...
    }
    

    Note: currentScript cannot be used directly in the constructor() for some reasons explained in this post.