当前位置:网站首页>Web components - Basics
Web components - Basics
2022-06-25 19:33:00 【Front end of panda Science】
background

Web Components What is it? ? seeing the name of a thing one thinks of its function , Namely “ Web components ”, Let's take a look first MDN How is it described in :
Web Components It's a group. web Platform technology API , Allows you to create reusable custom elements ( Their functionality is encapsulated outside your code ) And in your web Use them in your application .
from MDN From the description ,Web Components There are several key words : technology API, reusable 、 customized .
Next, let's learn in detail what good improvements this technology has made to our front-end development .
Under the current development background of large front-end ,React、Vue、Angular All of them support component-based development , You can separate the front-end interface into different components , Independent encapsulation style and interaction details , And through events / Property to communicate with other components , In traditional HTML Although we can also pass HTML Label packaging , But the problem is that there will be style pollution ,DOM Structure nesting is disordered , Unable to isolate and so on , and Web Components The emergence of has solved these problems well , Let's use native Web Technology to achieve something similar to React And other components .
Web Components The composition of
Web Components Not a single specification , It's a series of technologies , Include Custom Element、Shadow DOM、HTML templates Three technical specifications .
Custom elements
A group of JavaScript API, Allows you to define custom elements And their behavior , You can then use them as needed in your user interface .
Shadow DOM
A group of JavaScript API, Used to encapsulate “ shadow ”DOM Trees are attached to elements ( With the main document DOM Present separately ) And control its associated functions . In this way , You can keep the functionality of the element private , So they can be scripted and stylized , Don't worry about conflict with the rest of the document .
HTML templates
<templete> and <slot> Element allows you to write markup templates that are not displayed in the rendering page . Then they can be reused many times as the basis for a custom element structure .
Compatibility
About the above 3 Compatibility of this technology , We can refer to the following links :
- https://caniuse.com/?search=custom%20elements
- https://caniuse.com/?search=shadow%20dom
- https://caniuse.com/?search=html%20templates
Next, let's take a look at a web components this 3 What are the action points of these technologies ?
Custom Elements
Throw the code first :
<script>
class HelloHockor extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({
mode: "open",
});
const div = document.createElement("div");
div.className = "hello";
// Will not pollute the outside world
const style = document.createElement("style");
style.innerHTML = `
.hello {
color: red;
}
`;
div.innerHTML = "hello world";
shadow.appendChild(div);
shadow.appendChild(style);
}
}
const tagName = "hello-hockor";
// Determine whether this... Has been defined in the page tag
const isDefined = customElements.get(tagName);
if (!isDefined) {
customElements.define(tagName, HelloHockor);
}
</script>
Let's explain in detail
- First we define a class Hello World, Inherited from HTMLElement
- In the class Of constructor Inside , We can go through this.attachShadow To create a shadow dom
- stay shadow dom Inside, we can browse the native DOM Method to create a standard HTML label , Add content
- Finally, we passed customElements.define To define the tag name we output .
CustomElementRegistry
CustomElementRegistry Interface provides methods for registering custom elements and querying registered elements , To get an instance of it , Please use window.customElements attribute .
Detailed document address :https://developer.mozilla.org/zh-CN/docs/Web/API/CustomElementRegistry
We mainly use it here to define a new tag , The method accepts the following 3 Parameters :
- Represents the name of the created element
DOMStringStandard string . Be careful ,custom element The name of cannot be a single word , And among them There has to be a short line . - Used to define the behavior of an element class .
Optional parameters, A containextendsProperty , Is an optional parameter . It specifies which built-in element the created element inherits from , You can inherit any built-in element .
summary
Through the above JS The definition of , We can be in the ordinary DOM Use this tag To render our customized content , This tag It is controlled by ourselves , And if you open the console , You will see that its interior is wrapped in shadow-root Inside , And its internal style does not affect the style of external similar names .

demo Address :https://g8vtnv.csb.app/1.html
Template
In the example above , We are shadow Pass through document.createElement And create the structure we need internally , But this process style of writing is very laborious and thankless , For example, you now need to modify DOM Nesting order of , You have to rewrite a long list of dom operation , Or you want to change a property later , It's also very troublesome , Or our common declarative structure is convenient , So this leads us to web components The second key content in - template.
Let's first look at how to web components Use in template
<div id="app">
<div class="hello">i'm from browser</div>
<hello-world></hello-world>
<!-- The template section -->
<template id="hello">
<style>
.hello {
color: red;
}
</style>
<div class="hello">hello world</div>
</template>
</div>
<script>
class HelloWorld extends HTMLElement {
constructor () {
super()
const shadow = this.attachShadow({
mode: 'open'
})
// Here we directly get the template
const div = document.getElementById('hello')
shadow.appendChild(div.content.cloneNode(true))
}
}
customElements.define('hello-world', HelloWorld)
</script>
Notice here , We use Node.cloneNode() Methods will template Add content to shadow-root in .
demo Address :https://zl1xtk.csb.app/2.template.html
slot
be familiar with Vue My little friend may have used vue Medium slot, You can take a place in the template first , In the future, we will flexibly introduce our own defined DOM, And in the template in , Also support slot Of , Let's look at an example .
<div id="app">
<div class="hello">i'm from browser</div>
<hello-world>
<!--slot application -->
<span slot="username">hockor</span>
</hello-world>
<!-- The template section -->
<template id="hello">
<style>
.hello {
color: red;
}
</style>
<div class="hello">
hello,
<slot name="username">world</slot>
</div>
</template>
</div>
<script>
class HelloWorld extends HTMLElement {
constructor () {
super()
const shadow = this.attachShadow({
mode: 'closed'
})
const div = document.getElementById('hello')
shadow.appendChild(div.content.cloneNode(true))
}
}
customElements.define('hello-world', HelloWorld)
</script>
above demo We define by default slot It's a world, But the final rendering will be used by us <span slot="username">hockor</span> To replace , You can even pass in one nesting DOM structure , It's convenient for us to use .
demo Address :https://zl1xtk.csb.app/3.template-slot.html
Shadow DOM
And then finally, let's see web components Medium shadow dom, In fact, we have used it before , Just no formal introduction .
To borrow MDN Introduction to :Web components An important property of is encapsulation —— You can put the tag structure 、 Style and behavior are hidden , And isolated from other code on the page , Make sure the different parts don't mix together , Can make the code cleaner 、 Clean and tidy . among ,Shadow DOM The interface is the key , It can take a hidden 、 independent DOM Attach to an element 
here , There are several Shadow DOM Unique terms :
- Shadow host: A routine DOM node ,Shadow DOM Will be attached to this node .
- Shadow tree:Shadow DOM Inside DOM Trees .
- Shadow boundary:Shadow DOM Where it ends , It's also routine DOM Starting place .
- Shadow root: Shadow tree The root node .
mode attribute
const shadow = this.attachShadow({
mode: 'open'
})
In the example above, we create shadow When there is a pass mode, His optional values are open / closed
So what's the difference ? It's very simple , When we mode = closed When , We go through this.shadowRoot It's a null, Then you can't get it from the outside Shadow DOM 了 , This is the case with some built-in elements in browsers , for example <video>, Contains inaccessible Shadow DOM.
summary
Okay , about web components Let's go here first , For a component that can actually be used in a project , We definitely need to have a life cycle and CSS Style definition , We will continue to look at it later this 2 A question .
Reference link

边栏推荐
- QQ机器人疫情查询/疫情关注等【最新beta2版本】
- 请问同花顺开户安全吗?
- Network security detection and prevention test questions (II)
- ECS 7-day practical training camp (Advanced route) -- day04 -- build a portal using ECs and polardb
- Google cloud SSH enable root password login
- QQ机器人:群成员自我禁言管理【最新beta2版本】
- Error record: preg_ match(): Compilation failed: range out of order in character class at offset 13
- 二、HikariCP獲取連接流程源碼分析二
- Process of vacuum and vacuum full
- DARKHOLE 2
猜你喜欢

Apifox simple understanding -- the integrator of web side testing

Connecting PHP to MySQL instances in the lamp environment of alicloud's liunx system

QQ机器人疫情查询/疫情关注等【最新beta2版本】

Genicam gentl standard ver1.5 (1)
Android Development Notes - Quick Start (from sqllite to room licentiousness) 2
![[C language practice - print the upper triangle and its deformation (with blank version)]](/img/df/f38dc57c6a2de522acd91929ced1ad.png)
[C language practice - print the upper triangle and its deformation (with blank version)]

SEO outsourcing reliable company, enterprise SEO outsourcing company which reliable?

LeetCode-78-子集

Can GoogleSEO only do content without external chain? (e6zzseo)

削足适履 - 谈谈赛道上的坡道改造
随机推荐
Electronic package to generate EXE file
Laravel validation rule followed Role of auth:: id()
Jump jump games auxiliary (manual version) py code implementation
Analysis on employment compensation of 2021 college graduates: the average monthly starting salary of doctors, masters, undergraduates and junior colleges is 14823 yuan, 10113 yuan, 5825 yuan and 3910
Kotlin Compose 终结toDo项目 点击可以编辑修改todo
Do you want to know how new investors open accounts? Is online account opening safe?
R language uses the model of DALEX package_ The profile function interprets the relationship between a continuous feature and the target value Y in multiple classification models based on the conditio
Apifox simple understanding -- the integrator of web side testing
Tiger DAO VC产品正式上线,Seektiger生态的有力补充
Vulnhub range - the planes:venus
Miner's Diary: why should I go mining on April 5, 2021
Guangzhou Sinovel interactive VR panorama brings development to all walks of life
MySQL prompt performance_ Schema missing table
请问同花顺开户安全吗?
网络安全检测与防范 测试题(一)
Detailed explanation of oauth2 - Introduction (I)
Connecting PHP to MySQL instances in the lamp environment of alicloud's liunx system
PHP synchronizes website content to hundreds of websites to improve SEO ranking
QQ机器人:群成员自我禁言管理【最新beta2版本】
Leetcode-101-symmetric binary tree