【发布时间】:2017-02-07 14:03:19
【问题描述】:
我是网络组件的新手。我检查了一些示例,但我真的不知道如何加载(插入 DOM)单独 Web 组件的内容。从thisexample 开始,我将这段代码放在一个名为 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,我有什么要改变的?
谢谢
【问题讨论】:
标签: javascript web-component custom-element html-imports html5-template