此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

CustomElementRegistry

基线 广泛可用 *

自 2020年1月 起,此特性已在主流浏览器中得到支持,可在大多数设备和浏览器版本中正常使用。

* 此特性的某些部分的支持程度可能有所不同。

CustomElementRegistry 接口提供注册自定义元素和查询已注册元素的方法。要获取它的实例,请使用 window.customElements属性。

实例方法

CustomElementRegistry.define()

定义一个新的自定义元素

CustomElementRegistry.get()

返回指定自定义元素的构造函数,如果未定义自定义元素,则返回 undefined

CustomElementRegistry.getName()

返回已定义的自定义元素的名称,如果没有定义自定义元素,则返回 null

CustomElementRegistry.upgrade()

直接更新一个自定义元素,即使在它尚未连接到其影子根之前。

CustomElementRegistry.whenDefined()

返回当使用给定名称定义自定义元素时将会兑现的 Promise。如果已经定义了这样一个自定义元素,那么立即兑现返回的 promise。

示例

以下代码来自我们的 word-count-web-component 示例(查看实时运行版本)。请注意我们如何使用 CustomElementRegistry.define() 方法在创建其类后定义自定义元素。

js
// Create a class for the element
class WordCount extends HTMLParagraphElement {
  constructor() {
    // Always call super first in constructor
    super();

    // count words in element's parent element
    var wcParent = this.parentNode;

    function countWords(node) {
      var text = node.innerText || node.textContent;
      return text.split(/\s+/g).length;
    }

    var count = "Words: " + countWords(wcParent);

    // Create a shadow root
    var shadow = this.attachShadow({ mode: "open" });

    // Create text node and add word count to it
    var text = document.createElement("span");
    text.textContent = count;

    // Append it to the shadow root
    shadow.appendChild(text);

    // Update count when element content changes
    setInterval(function () {
      var count = "Words: " + countWords(wcParent);
      text.textContent = count;
    }, 200);
  }
}

// Define the new element
customElements.define("word-count", WordCount, { extends: "p" });

规范

规范
HTML
# custom-elements-api

浏览器兼容性