网络组件(香草,没有聚合物):如何加载<模板>内容? [英] web component (vanilla, no polymer): how to load <template> content?
问题描述
我是网络组件的新手。我检查了一些例子,但我真的无法弄清楚如何加载(插入DOM)一个单独的Web组件的内容。从这个示例开始,我将此代码放在一个名为的文件中my-element.html:
i'm new on web component. I checked some example, but i really can't figure out how to load (insert in the DOM) the content of a of a separate web component. Starting from this example , I put this code in a file named 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:
This is my 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,所以我不需要填充。我运行polyserve,只有它有效吗?出现。我尝试(像原始示例)customElements.define语法而不是document.registerElement,但不起作用。你有什么想法吗?如果我不想使用影子dom,我还能改变什么?
I'm on latest Chrome 56, so i don't need polyfill. I run polyserve, and only "Does it works?" appears. I tried (like the original example) the "customElements.define" syntax instead of "document.registerElement", but won't work. Have you some ideas? And what have I to change if i don't want to use shadow dom?
谢谢
推荐答案
这是因为当你这样做时:
It's because when you do:
document.querySelector( '#my-element' );
... 文件
指的是主要的document index.html
...document
refers to the main document index.html
如果你想获得模板,你应该使用 document.currentScript.ownerDocument
If you want to get the template, you should use instead 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
调用中)
Note that document.currentScript
is a global variable, so it refers to your imported document only when it is currently parsed. That's why it's value is saved in a variable (here: importedDoc
) to be reusable later (in the constrcutor
call)
如果您有多个导入的文档,您可能希望将其隔离在一个闭包中(如在这篇文章中):
If you have multiple imported document you may want to isolate it in a closure (as explained in this post):
( function ( importedDoc )
{
//register element
} )(document.currentScript.ownerDocument);
这篇关于网络组件(香草,没有聚合物):如何加载<模板>内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!