从模板自定义元素获取内容时出错

error getting content from template customelement

我有一个基本的 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>

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

Uncaught TypeError: Cannot read property 'content' of null

这是因为 const template 总是 null。这以前是有效的,但我不知道是否有任何改变,现在它不起作用了。我正在使用 Chrome 版本 62.0.3202.94(官方构建)(64 位) 请问有什么帮助吗?

试试这个:

<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 文件的全局 space 中访问。

I always use both together to work with all of the web-component polyfills. If you don't need the polyfill, by limiting the browsers you support, then you can just use document.currentScript.