CustomElementRegistry
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.
**CustomElementRegistry
**接口提供注册自定义元素和查询已注册元素的方法。要获取它的实例,请使用 window.customElements
属性。
方法
CustomElementRegistry.define()
-
定义一个新的自定义元素。
CustomElementRegistry.get()
-
返回指定自定义元素的构造函数,如果未定义自定义元素,则返回
undefined
。 CustomElementRegistry.upgrade()
-
Upgrades a custom element directly, even before it is connected to its shadow root.
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" });
规范
Specification |
---|
HTML Standard # custom-elements-api |
浏览器兼容性
BCD tables only load in the browser