HTML Import: How to obtain correct document object within imported html?

115 Views Asked by At

https://www.webcomponents.org/community/articles/introduction-to-html-imports#window-and-document-object-in-an-imported-html suggests to use var mainDoc = document.currentScript.ownerDocument; in order to get the imported document so that any templates/elements within it can be queried like maidDoc.querySelector('#someid'). This works fine with single level imports; but is failing when there are multiple levels of import. See the following example:

Index.html

<head>
    <link rel="import" href="components/global/site-navigation.html">    
</head>
<body>    
    <site-navigation></site-navigation>
</body>

site-navigation.html

<link rel="import" href="nav-item.html">
<template>    
    <div class="nav">Header Goes here</div>
    <ul class="nav">
        <nav-item target="http://example.com" toolTip="Example"></nav-item>
    </ul>
</template>
<script>
    customElements.define('site-navigation', class SiteNavigation extends HTMLElement {
        constructor() {
            super();
            const currentDocument = document.currentScript.ownerDocument;
            const shadowTemplate = currentDocument.querySelector('template').content.cloneNode(true);
            this.DOM = this.attachShadow({ mode: 'open' });
            this.DOM.appendChild(shadowTemplate);            
        }

        connectedCallback(){
            this.Initialize();
        }

        Initialize(){
            this.DOM.querySelector("div.nav").innerHTML = "Hello world!"
        }
    });
</script>

nav-item.html

<template>
    <li class="nitem">
        <a href="#">Elements</a>
    </li>
</template>
<script>
    customElements.define('nav-item', class SiteNavigationItem extends HTMLElement {
        constructor() {
            super();
            const currentDocument = document.currentScript.ownerDocument;
            const shadowTemplate = currentDocument.querySelector('template').content.cloneNode(true);
            this.DOM = this.attachShadow({ mode: 'open' });
            this.DOM.appendChild(shadowTemplate);
        }

        connectedCallback(){
            this.Initialize();
        }

        Initialize(){
            let aTag = this.DOM.querySelector('li.nitem > a');
            aTag.innerHTML = "Hello world!"
        }
    });
</script>

When debugging with Chrome developer tools, document.currentScript.ownerDocument in the nav-item.html returns the same document returned from it's parent (site-navigation.html). Thus I get wrong content when currentDocument.querySelector('template').content.cloneNode(true) is executed. In this case it causes stack overflow exception! See the screen shot below: enter image description here

0

There are 0 best solutions below