【问题标题】:web component (vanilla, no polymer): how to load <template> content?Web 组件(香草,无聚合物):如何加载 <template> 内容?
【发布时间】: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


    【解决方案1】:

    这是因为当你这样做时:

    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);
    

    【讨论】:

    • 谢谢!!所以“document.registerElement”也是不正确的。
    • 如果你想使用 registerElement() 你应该用 createdCallback() 替换 constructor()。但最好使用新的标准化版本 customElements.define()。
    • 太棒了!谢谢你
    猜你喜欢
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 2014-09-16
    • 2016-09-04
    • 2015-01-24
    • 1970-01-01
    相关资源
    最近更新 更多