Lesson 13-HTML5 Web Component Technology Application

HTML5 Web Components technology is a collection of related standards and APIs that aims to enhance componentization capabilities in Web development, allowing developers to create reusable, well-encapsulated custom UI components that have independent view layers (styles), logic (behavior), and structures (templates). Web Components mainly include the following four core technologies:

Custom Elements

Custom Elements allow developers to define their own HTML tags, extending the semantic tagging system of HTML. By creating new element classes and registering them with the browser, developers can create custom components with specific functions and behaviors, such as <my-accordion>, <x-carousel>, etc. These custom elements can be used directly in the page like built-in HTML elements, with complete life cycle management, including:

constructor(): called when the element is created.

connectedCallback(): called when the element is inserted into the DOM.

disconnectedCallback(): called when the element is removed from the DOM.

adoptedCallback(): called when the element is moved to a new document (not commonly used).
attributeChangedCallback(): Called when the attribute of the element changes (if observing specific attribute changes is implemented).
Custom elements make components more encapsulated, the code more modular, and not limited to a specific framework or library, with cross-framework compatibility.

Shadow DOM

Shadow DOM provides an independent DOM tree (shadow DOM tree) and style isolation mechanism for Web components. The HTML structure and CSS style inside the component are encapsulated in Shadow DOM and will not affect the style of the external document, and vice versa. Create a shadow root node by using the attachShadow() method and attach the internal structure of the component to this node. Shadow DOM supports the following features:
Style encapsulation: The styles inside the component will not leak to the outside, and the external styles will not interfere with the internal components unless selectors such as :host, ::slotted, or /deep/ (deprecated) are explicitly used.
DOM encapsulation: The DOM nodes inside the component are invisible to external code, providing better data hiding and component boundaries.
Event encapsulation: Events are captured and bubbled inside Shadow DOM, which can prevent external code from accidentally interfering with component internal event processing.

HTML Templates

HTML Templates define reusable HTML fragments through the <template> tag, which are not parsed and rendered when the page is loaded until they are dynamically instantiated through JavaScript. Templates can contain any legal HTML elements and scripts, but will not affect the initial page loading performance. Combined with the <slot> element, templates can implement content distribution (content projection), allowing external content to be injected into predefined locations inside components, enhancing the flexibility and configurability of components.

HTML Imports

HTML Imports are no longer supported by modern browsers and have been replaced by modular systems (such as ES6 modules).
Historical information: HTML Imports was originally planned as part of Web Components to import another HTML file (which may contain custom elements, templates, etc.) in one HTML file. This helps organize and reuse component resources. However, due to insufficient support from browser vendors and the rise of modular solutions, HTML Imports has gradually been eliminated.

Web Components technology brings the following advantages to Web development:

  • Encapsulation: Encapsulation of styles and DOM is achieved through Shadow DOM, reducing global namespace conflicts.
  • Reusability: Custom elements are independent units that can be easily reused in different projects, pages, and even across frameworks.
  • Modularity: Each component has its own HTML, CSS, and JavaScript, following the principle of separation of concerns.
  • Custom semantics: Through custom elements, tags with specific business meanings can be created to improve code readability.
  • Framework-independent: Web Components is a standard natively supported by browsers and can be used without relying on a specific front-end framework.

Although Web Components itself is natively supported by browsers, in actual development, in order to be compatible with older browsers that do not fully support these features, libraries or frameworks such as Polymer, Stencil.js, and LitElement may be needed to provide additional cross-browser support. As modern browsers increase their support for Web Components, more and more projects are starting to use native APIs directly for component development.

The following are the basic steps to create a simple Web Component, taking <my-element> as an example:

Define Custom Element:

Use window.customElements.define() method to define a new custom element:

   class MyElement extends HTMLElement {
       constructor() {
           super(); // Calling the superclass constructor
           this.attachShadow({ mode: 'open' }); // create Shadow DOM
       }

       connectedCallback() {
           this.shadowRoot.innerHTML = `
               <style>
                   /* Add CSS here */
                   .my-element {
                       background-color: lightblue;
                       padding: 16px;
                       border: 1px solid blue;
                       display: flex;
                       align-items: center;
                       justify-content: center;
                   }
               </style>
               <h1>Hello, World!</h1>
           `;
       }
   }

   customElements.define('my-element', MyElement);

In this example, we create a new element called my-element, which has an inner Shadow DOM containing a <style> tag for style isolation, and a <h1> element to display text.

Using Custom Element:

In an HTML document, you can use <my-element> like any other HTML element:

   <!DOCTYPE html>
   <html lang="en">
   <head>
       <meta charset="UTF-8">
       <title>My Custom Element</title>
   </head>
   <body>
       <my-element></my-element>
       <script src="my-element.js"></script>
   </body>
   </html>

my-element.js is the file containing the above JavaScript code, which defines the MyElement class.

Interactions and events:

Custom elements can have their own properties, methods, and event listeners. For example, you can add a message property and a sayHello method to the MyElement class:

   class MyElement extends HTMLElement {
       // ...
       get message() {
           return this.getAttribute('message') || 'Hello, World!';
       }

       set message(value) {
           this.setAttribute('message', value);
       }

       sayHello() {
           alert(this.message);
       }

       // ...
   }

Then in your HTML, you can set the message property and respond to user click events:

   <my-element message="Custom Message"></my-element>
   <button onclick="document.querySelector('my-element').sayHello()">Say Hello</button>
Share your love