Web Components Technical Analysis

Briefly:

Web Components are based on four main specifications: Custom Elements, Shadow DOM, HTML Templates and HTML Imports.

Custom Elements allows developers to create custom HTML tags.

 Shadow DOM allows developers to encapsulate style and behavior inside custom elements without affecting the surrounding Web pages.

HTML Templates can store HTML fragments for reference when needed.

HTML Imports allows developers to organize and import Custom Elements and HTML Templates in a modular way.

Custom Elements and Shadow DOM are the two most important APIs (specifications), and they are also the underlying implementation logic of micro-app and wujie. 

micro-app mainly relies on (web Component and proxy implementation)

Here is a code that shows how to use these two important APIs: 

1. const shadowRoot = this.attachShadow({ mode: 'open' });       attachShadow: Create a shadowDOM, which encapsulates the style and behavior of the component in a "closed" subtree by using Shadow DOM.

2. customElements.define('my-element', MyElement);                   customElements.define() method, register the MyElement class as a custom element

// 以下是一个示例代码:


<template id="my-element-template">
  <style>
    :host {
      background-color: lightblue;
      display: block;
      padding: 20px;
      border-radius: 5px;
    }
  </style>
  <div>
    <h1>Hello, World!</h1>
    <p>This is my custom element.</p>
  </div>
</template>

<script>
  class MyElement extends HTMLElement {
    constructor() {
      super();

      const template = document.getElementById('my-element-template');
      const templateContent = template.content.cloneNode(true);
      const shadowRoot = this.attachShadow({ mode: 'open' });
      shadowRoot.appendChild(templateContent);
    }
  }

  customElements.define('my-element', MyElement);
</script>
```

在这个示例中,我们定义了一个 MyElement 类,这个类是一个自定义元素,它通过使用 Shadow DOM,将组件的样式和行为封装在一个“封闭”的子树中。在构造函数中,我们通过使用 template 和 cloneNode 方法,将 Shadow DOM 填充为组件的内容。

最后,我们通过调用 customElements.define() 方法,将 MyElement 类注册为自定义元素,从而可以在页面中使用它。

Shadow DOM tree display diagram: 

MDN example: 

Guess you like

Origin blog.csdn.net/weixin_43416349/article/details/130160393