Window.customElements

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.

customElementsWindow 对象上的一个只读属性,接口返回一个 CustomElementRegistry 对象的引用,可用于注册新的 custom element,或者获取之前定义过的自定义元素的信息。

例子

这个属性最常用的例子是用来获取使用CustomElementRegistry.define()方法定义和注册的自定义元素,例如:

js
let customElementRegistry = window.customElements;
customElementRegistry.define("my-custom-element", MyCustomElement);

However, it is usually shortened to something like the following:

js
customElements.define(
  "element-details",
  class extends HTMLElement {
    constructor() {
      super();
      const template = document.getElementById(
        "element-details-template",
      ).content;
      const shadowRoot = this.attachShadow({ mode: "open" }).appendChild(
        template.cloneNode(true),
      );
    }
  },
);

参阅我们的 web-components-examples 获取更多有用的例子。

规范

Specification
HTML
# dom-window-customelements

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
customElements

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support