从模板customelement获取内容时出错

时间:2017-11-28 19:14:26

标签: javascript web-component shadow-dom custom-element

我有一个基本的CustomElement但是我遇到了以下问题:

<template id="custom-element">
  <h1>Example 1</h1>
</template>

<script>

  class CustomElement extends HTMLElement {

    constructor() {
      super(); // always call super() first in the ctor.
      let shadowRoot = this.attachShadow({mode: 'open'});
      const template = document.querySelector('#custom-element');
      const instance = template.content.cloneNode(true);
      shadowRoot.appendChild(instance);
    }
    connectedCallback() {
      console.log("Connected");
    }

    disconnectedCallback() {

    }

    attributeChangedCallback(attrName, oldVal, newVal) {

    }
  }

  window.customElements.define('custom-element', CustomElement);

</script>

我在控制台中收到此错误:

  

未捕获的TypeError:无法读取null

的属性'content'

这是因为const template总是 null 。这之前有用,但我不知道是否有任何改变,现在它不起作用。我正在使用Chrome版本62.0.3202.94(官方版本)(64位) 对此有何帮助?

1 个答案:

答案 0 :(得分:0)

试试这个:

<template id="custom-element">
  <style>
  h1 {
    color: red;
    font: bold 24px Tahoma;
  }
  </style>
  <h1>Example 1</h1>
</template>
<script>
  const template = (document.currentScript||document._currentScript).ownerDocument.querySelector('#custom-element').content;

  class CustomElement extends HTMLElement {
    constructor() {
      super(); // always call super() first in the ctor.
      let shadowRoot = this.attachShadow({mode: 'open'});
      let instance = template.cloneNode(true);
      shadowRoot.appendChild(instance);
    }
    connectedCallback() {
      console.log("Connected");
    }

    disconnectedCallback() {
    }

    attributeChangedCallback(attrName, oldVal, newVal) {
    }
  }

  window.customElements.define('custom-element', CustomElement);
</script>

您需要在构造函数之前获取document.currentScript||document._currentScript必须才能在导入的HTML文件的全局空间中访问。

  

我总是同时使用它们来处理所有的Web组件polyfill。如果您不需要填充,通过限制您支持的浏览器,那么您可以使用document.currentScript