1

https://www.webcomponents.org/community/articles/introduction-to-html-imports#window-and-document-object-in-an-imported-html建议使用var mainDoc = document.currentScript.ownerDocument;以获取导入的文档,以便任何其中的模板/元素可以像maidDoc.querySelector('#someid'). 这适用于单级导入;但是当有多个导入级别时失败。请参见以下示例:

索引.html

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

网站导航.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>

导航项.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>

使用 Chrome 开发人员工具进行调试时,document.currentScript.ownerDocument在 nav-item.html 中返回从其父级 (site-navigation.html) 返回的相同文档。因此,执行时我得到错误的内容currentDocument.querySelector('template').content.cloneNode(true)。在这种情况下会导致堆栈溢出异常!请看下面的屏幕截图: 在此处输入图像描述

4

0 回答 0