Web Components related concepts

Web Components are getting more and more attention. In 2019, Microsoft’s Edge team announced support for Custom Elements and Shadow Dom on Edge, and Web Components are now supported in all major browsers.

In addition, some foreign companies, such as Github, Netflix, Youtube and ING, have even used Web Components in production environments.

🙋 What are web components?

Web Components is a set of standards that allow developers to create new custom, reusable, encapsulated HTML elements for use in Web pages and Web applications. Custom components and widgets build on the Web Components standard, work across modern browsers, and can be used with any JavaScript library or framework. Web Components are based on existing Web standards. Features supporting Web Components are currently being added to the HTML and DOM specifications, allowing Web developers to easily extend HTML by encapsulating styles and custom behavior. Source: https://www.webcomponents.org/introduction Web Components are of a different technology, allows you to create reusable custom element (their function encapsulation in your code) and use them in your Web application source:  https://developer.mozilla.org/zh-CN/docs/Web/Web_ComponentsCopy the code

✨ highlight

First: Web Components are a set of standards, made up of different technologies, that allow us to write modular, reusable, and encapsulated HTML elements.

Best of all: Since they are based on Web standards, we don’t need to install any frameworks or libraries to start using them. You can write Web components in plain Old javascript!

📂 use

As developers, we all want to reuse as much code as possible. This is often not so easy for custom UI controls – think of complex HTML (and associated styles and scripts), and sometimes you have to write a lot of code to render custom UI controls, and the only way to reuse custom UI controls without relying on any framework is to paste and copy the code.

Web Components aims to solve these problems-it consists of three major technologies that can be used together to create custom elements that encapsulate specific functionality and can be reused anywhere you like without worrying about code or style conflicts.

Brief introduction of three main technologies:

1.Custom elements

A set of JavaScript apis that allow you to define Custom Elements and their behavior, which can then be used as needed in your user interface. The simple explanation is that the HTML elements are user-defined. They register a new element by using CustomElementRegistry, and get the registered instance through a method called define in window.customElements

 window.customElements.define('my-element', MyElement);
Copy the code

The first parameter in the method defines the tag name of the newly created element, which we can easily use directly

<my-element></my-element>
Copy the code

To avoid conflicts with native tags, custom tags are forced to use hyphens.

2.Shadow DOM

A set of JavaScript apis for attaching encapsulated “shadow “DOM trees to elements (rendered separately from the main document DOM) and controlling the functionality associated with them. In this way, you can keep the functionality of elements private so that they can be scripted and styled without fear of conflict with other parts of the document.

An important attribute of Web Components is encapsulation — the ability to hide tag structure, style, and behavior from the rest of the code on the page, ensuring that different parts don’t get mixed up, making the code cleaner and cleaner. The key is the Shadow DOM interface, which can attach a hidden, independent DOM to an element.

useShadow DOM, the custom elementHTML å’Œ CSSFully encapsulated within the component. This means that the element will be in a singleHTMLThe tag appears in the document’sDOMTree species. Its internal structure will be placed in#shadow-root.

The Shadow DOM keeps HTML and CSS separate from the DOM of the main document.

Note: Firefox (starting with version 63), Chrome, Opera, and Safari support Shadow DOM by default. The new Chromium-based Edge also supports Shadow DOM; The old Edge did not survive long enough to support this feature.

Why separate some code from the rest of the code on the page?

For one thing, if the CSS is not well organized on a large site, the navigation style can “leak” into places where it should not, such as the main content area, and vice versa. As sites and applications expand, this is inevitable.

To recognize

In fact, some native HTML elements also use Shadow DOM. For example, if you have a

These controls are actually part of the Shadow DOM of the video element and are therefore hidden by default. To display the Shadow DOM in Chrome, go to Preferences in the developer tools and select Show User Agent Shadow DOM. When you look at the video element again in the developer tools, you will see the Shadow DOM for that element.

Detailed operation steps are as follows:

Note:

Shadow DOM isn’t new by any means — it’s been used by browsers for a long time to encapsulate the internal structure of some elements. Take a

attribute

Shadow DOMThe permission will be hiddenDOMTree attached to the regularDOM In the tree — it takesshadow rootThe node is the starting root node, and below this root node, can be any element, and ordinaryDOMSame with the elements.

Here are some Shadow DOM specific terms to know:

  • Shadow host: A routineDOMNode,Shadow DOMWill be attached to this node.
  • Shadow tree:Shadow DOMThe internal DOM tree.
  • Shadow boundary:Shadow DOMWhere it ends, it’s routineDOMThe place to start.
  • Shadow root: Shadow treeThe root node of.

Basic usage

You can attach a shadow root to any Element using the element.attachShadow () method. It takes as an argument a configuration object that has a mode property that can be open or closed:

let shadow = elementRef.attachShadow({ mode: 'open' })
let shadow = elementRef.attachShadow({ mode: 'closed' })
Copy the code

Open means that the Shadow DOM can be obtained using JavaScript methods within the page, such as the Element. ShadowRoot property:

let myShadowDom = myCustomElem.shadowRoot
Copy the code

If you attach a Shadow root to a Custom element and set mode to closed, It is no longer possible to retrieve the Shadow DOM from outside — myCustomElem. ShadowRoot will return null. This is true of some built-in elements in the browser, such as

If you want to attach a Shadow DOM to a Custom element, you can add the following implementation to the Custom Element constructor (currently, this is the most useful use of the Shadow DOM) :

let shadow = this.attachShadow({ mode: 'open' })
Copy the code

After attaching the Shadow DOM to an element, you can use the DOM APIs to manipulate it just as you would a regular DOM.

var para = document.createElement('p')
shadow.appendChild(para)
Copy the code

Templates (HTML)

The

In addition to using this. ShadowRoot. InnerHTML to an element of shadow root to add HTML, you can also use the < template > to do it. The template saves the HTML for later use. It is not rendered and is parsed only to ensure that the content is valid. The JavaScript in the template will not be executed and will fetch any external resources, which is hidden by default.

When a Web Component needs to render different tags for different situations, different templates can be used to do so

In the Wheat-UI Button component because the Button component renders different labels based on different properties

// Both tags are created
const template = document.createElement('template')
const templateTagA = document.createElement('template')
template.innerHTML = ` 
      
`
templateTagA.innerHTML = ' ' // When rendering, we will render different templates according to the href this._shadowRoot = this.attachShadow({ mode: 'open' }) this._shadowRoot.appendChild( this.href ? templateTagA.content.cloneNode(true) : template.content.cloneNode(true),Copy the code

cloneNode

The node.clonenode () method returns a copy of the Node on which it was called.

Var dupNode = node.clonenode (deep);Copy the code
  • Node Indicates the node to be cloned

  • DupNode Clone node

  • Deep Specifies whether to use deep cloning. If true, all descendants of the node are cloned. If false, only the node itself is cloned.

Cloning an element node copies all its attributes and attribute values, including events bound to the attribute (such as onclick=”alert(1)”), but not those that use the addEventListener() method or node.onclick = fn JavaScript dynamically bound events.

Until a copied Node is added to the document using node.appendChild () or another similar method, that copied Node is not part of the current document tree; that is, it has no parent Node.

If the deep parameter is set to false, none of its children will be cloned. Any Text contained by this node is also not cloned because the Text itself is also one or more Text nodes.

If the deep argument is set to true, the entire DOM subtree (including any Text children that might exist) is copied. For null nodes (such as and elements), it doesn’t matter whether the deep parameter is set to true or false, but you still need to specify a value for it.

The purpose of using cloneNode is; After obtaining the

Add the style

The custom element does not have a style yet. You can assign a global style to it, as shown below.

wheat-button {
  / *... * /
}
Copy the code

However, the styling of the component should be wrapped in the code and only apply to custom elements without affecting the external global styling. So, you can write the style inside

// Set the style
const style = ` .wheat-button { /* ... * /} `
// Use it in template
const template = document.createElement('template')
const templateTagA = document.createElement('template')
template.innerHTML = `
    ${style}<div class="wheat-button-container"> <button class='wheat-button'> <slot name='icon'/> Label </button> </div> `
templateTagA.innerHTML = '
      '
Copy the code

As with JQ before it, as Document.querySelector became widely supported by browsers, JQ began to be used less frequently. This can happen with Frameworks like Angular, React, and Vue