我是网络组件的新手。我检查了一些示例,但我真的不知道如何加载(插入 DOM 中)一个单独的 Web 组件的内容。从 this 开始例如,我将此代码放在名为 my-element.html 的文件中:
<template id="my-element">
<p>Yes, it works!</p>
</template>
<script>
document.registerElement('my-element', class extends HTMLElement {
constructor() {
super();
let shadowRoot = this.attachShadow({mode: 'open'});
const t = document.querySelector('#my-element');
const instance = t.content.cloneNode(true);
shadowRoot.appendChild(instance);
}
});
</script>
这是我的 index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>my titile</title>
<link rel="import" href="my-element.html">
</head>
<body>
Does it work?
<my-element></my-element>
</body>
</html>
我使用的是最新的 Chrome 56,所以我不需要 polyfill。我运行 polyserve,只有“它有效吗?”出现。我试过(像原来的例子一样)“customElements.define”语法而不是“document.registerElement”,但不起作用。你有什么想法吗?如果我不想使用 shadow dom,我需要更改什么?
谢谢
最佳答案
这是因为当你这样做时:
document.querySelector( '#my-element' );
...document
指的是主文档index.html
如果你想获取模板,你应该使用 document.currentScript.ownerDocument
var importedDoc = document.currentScript.ownerDocument;
customElements.define('my-element', class extends HTMLElement {
constructor() {
super();
let shadowRoot = this.attachShadow({mode: 'open'});
const t = importedDoc.querySelector('#my-element');
const instance = t.content.cloneNode(true);
shadowRoot.appendChild(instance);
}
});
请注意,document.currentScript
是一个全局变量,因此它仅在当前 解析时引用您导入的文档。这就是为什么它的值被保存在一个变量中(这里:importedDoc
)以便以后可以重用(在 constrcutor
调用中)
如果您有多个导入的文档,您可能希望将其隔离在一个闭包中(如 in this post 所述):
( function ( importedDoc )
{
//register element
} )(document.currentScript.ownerDocument);
关于javascript - Web 组件( Vanilla ,无聚合物): how to load <template> content?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42091849/