1
头图

foreword

In the previous article, I introduced the related concepts of Web Components, knowing that it is a method used by browsers to natively support "componentization", and that its technical components are:

  • Custom Elements
  • Shadow DOM
  • HTML templates

Today, let's learn part of the knowledge of one of its technologies - Custom Element.

Meaning of Custom Elements

A very important feature of the Web Components standard is that it enables developers to encapsulate the functionality of an HTML page as custom elements (custom tags), whereas in the past, developers had to write a lot of lengthy, deeply nested tags to achieve Same page functionality.

Custom Elements are the foundation and core of web componentization.

Classification of Custom Elements

Custom Elements are divided into two categories based on whether they inherit the underlying HTML elements.

Autonomous custom elements

is a stand-alone element that does not inherit other built-in HTML elements. You can directly write them in the form of HTML tags to use on the page. For example, <my-card> , or document.createElement("my-card") .

Customized built-in elements

Inherited from basic HTML elements. When creating, you must specify the element to be extended. When using, you need to write the basic element tag first, and specify the name of the custom element through the is attribute. For example <p is="my-card"> , or document.createElement("p", { is: "my-card" }) .

CustomElementRegistry object

We already know the concept of custom tags and other related knowledge, so how to use custom tags in actual development? Here we need to introduce the key object of Custom Elements - the CustomElementRegistry object.

To get an instance of it, use the window.customElements property. Its main functions are:

  • Register a custom tag for the page
  • Get information about registered Custom Elements

Let's take a look at the relevant methods of the CustomElementRegistry object:

image-20220207214934295

As you can see, the CustomElementRegistry object contains four methods:

  • CustomElementRegistry.define()
  • CustomElementRegistry.get()
  • CustomElementRegistry.upgrade()
  • CustomElementRegistry.whenDefined()

Next, we introduce each method of the CustomElementRegistry object separately.

CustomElementRegistry.define()

It is used to define (create) a custom tag. The syntax is as follows:

customElements.define(name, constructor, options);

Parameter parsing:

  • name Custom label name. Note: It cannot be a single word, and must have dashes, such as: my-card .
  • constructor Custom element constructor, which can control the expression, behavior and life cycle of elements.
  • options A configuration object containing extends properties, optional parameters. It specifies which built-in element the created element inherits from, and can inherit from any built-in element.

The return value is undefined.

Example of use:

// 声明自定义标签构造函数类
class MyCard extends HTMLParagraphElement{
    constructor(){
        super();
        ……
    }
}

// 注册自定义标签
customElements.define('my-card', MyCard, { extends: 'p' });

CustomElementRegistry.get()

This method is used to return the constructor of the custom label defined earlier. The syntax is as follows:

constructor = customElements.get(name);

name indicates the label name of the custom label constructor you want to get, and its format should also be a word connected by dashes.

Constructor for the custom element with the given name, or undefined if there is no custom element definition with that name.

Example of use:

// 调用 get 方法
customElements.get("my-card");

// class MyCard extends HTMLParagraphElement{
//     constructor(){
//         super();        
//     }
// }

customElements.get("MyCard");
// undefined

CustomElementRegistry.upgrade()

This method will update all custom elements in the root subtree that contain shadow DOMs, even before they load into the main document. The syntax is as follows:

customElements.upgrade(root);

root represents the Node instance with the shadow-containing descendant element to be promoted. No error is thrown if there are no descendant elements that can be upgraded.

Its return value is undefined.

Without calling the upgrade method:

const el = document.createElement("my-card");
class MyCard extends HTMLElement {}
customElements.define("my-card", MyCard);
console.log(el instanceof MyCard); // false

Call the upgrade method:

const el = document.createElement("my-card");
class MyCard extends HTMLElement {}
customElements.define("my-card", MyCard);
customElements.upgrade(el);
console.log(el instanceof MyCard); // true

CustomElementRegistry.whenDefined()

Returns the promise that will be executed when a custom element is defined with the given name. If such a custom element has already been defined, then the returned promise is executed immediately. The syntax is as follows:

Promise<> customElements.whenDefined(name);

name is also the name representing the custom label.

Example one:

class MyCard extends HTMLParagraphElement {
    constructor() {
        super();
    }
}

customElements.whenDefined("my-card").then(() => {
    console.log(`my-card 被注册`);
});
console.log("my-card 注册前");
customElements.define("my-card", MyCard, { extends: "p" });
console.log("my-card 注册后");

// my-card 注册前
// my-card 注册后
// my-card 被注册

If the following code is executed again, the resolve method will be executed immediately:

customElements.whenDefined("my-card").then((res) => {
    console.log(res);
    console.log(`my-card 被注册`);
});
// my-card 被注册

Summarize

The above are some of the knowledge points about Custom Elements, and the life cycle functions of custom tags will be added later.

~

~ This article is over, thanks for reading!

~

Learn interesting knowledge, meet interesting friends, and shape interesting souls!

Hello everyone, I'm King , the author of 〖 Programming Samadhi 〗, my official account is " Programming Samadhi ", welcome to pay attention, I hope you can give me more advice!


编程三昧
54 声望10 粉丝

学习有趣的知识,交识有趣的朋友,造就有趣的灵魂!