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')
。这适用于单级导入;但是当有多个导入级别时失败。请参阅以下示例:
的index.html
<head>
<link rel="import" href="components/global/site-navigation.html">
</head>
<body>
<site-navigation></site-navigation>
</body>
网站-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>
使用Chrome开发者工具进行调试时,nav-item.html中的document.currentScript.ownerDocument
会返回从其父级返回的相同文档(site-navigation.html)。因此,当currentDocument.querySelector('template').content.cloneNode(true)
执行时,我得到错误的内容。在这种情况下,它会导致堆栈溢出异常!
请参见下面的屏幕截图: