customElements.define
在MDN官方文档中,假如你想要运用自定义标签,能够运用customElement类中define要领(IE7以下浏览器不支持),
运用:customElements.define(‘myselfTagName’, myselfClass, extendsObj);
参数:
myselfTagName: 自定义标署名
myselfClass: 自定义标签的类对象,(主要功用在这里完成,平常在自定义标签绑定变量、事宜、指令或者是衬着前提)
extendsObj: 内置并继续的元素(包裹着自定义标签的对象,平常不运用,毕竟谁会闲的无聊把基础标签封装成自定义标签然后添补一堆属性,语义化也说不通啊)
attachShadow
官方文档关于shadow DOM诠释很隐约,简朴的说就是DOM的’一体双魂’,具有一样的函数和要领,然则Shadow DOM比被附加DOM更多的功用,前者具有单独的作用域,而且与外界DOM分开。(这个作用就是shadow DOM的中心功用,它能够使你编写的DOM与css与其他地区互不影响,相当于vue中css款式<style scoped> </style>的作用);
shadow DOM弥补了customElements缺乏断绝作用域(DOM和css作用域)的缺点。
shadom DOM Root的建立要领: this.attachShadow({mode: ‘open’});
this: shadom DOM对象
mode: 开启js挪用shadow DOM
代码树模
coding.... 莫道征途路漫漫
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pop-up info box — web components</title>
</head>
<body>
<h1>Pop-up info widget - web components</h1>
<form>
<div>
<label for="cvc">Enter your CVC <popup-info img="img/alt.png" data-text="Your card validation code (CVC) is an extra security feature — it is the last 3 or 4 numbers on the back of your card."></label>
<input type="text" id="cvc">
</div>
</form>
</body>
<script>
/**
*
* @description:将shadow root附加到customelement上,
然后经由过程一系列DOM操纵建立custom element的内部暗影DOM组织,
再将其附加到 shadow root上,末了再将一些CSS附加到
shadow root的style节点上。
*/
class PopUpInfo extends HTMLElement {
constructor() {
// 必需运用super初始化customElements类的组织器
super();
// 建立shadom Dom Root,该Root 挂载在自定义DOM上,该DOM Root节点是一个实在节点。
const shadow = this.attachShadow({mode: 'open'});
// Create spans
const wrapper = document.createElement('span');
wrapper.setAttribute('class', 'wrapper');
let icon = document.createElement('span'),
info = document.createElement('span'),
text = this.getAttribute('data-text');
icon.setAttribute('class', 'icon');
icon.setAttribute('tabindex', 0);
info.textContent = text;
info.setAttribute('class', 'info');
let imgUrl = this.hasAttribute('img') ? this.getAttribute('img'): 'img/default.png',
img = document.createElement('img');
img.src = imgUrl;
icon.appendChild(img);
// 优化款式
const style = document.createElement('style');
console.log(style.isConnected);
style.textContent = `
.wrapper {
position: relative;
}
.info {
font-size: 0.8rem;
width: 200px;
display: inline-block;
border: 1px solid black;
padding: 10px;
background: white;
border-radius: 10px;
opacity: 0;
transition: 0.6s all;
position: absolute;
bottom: 20px;
left: 10px;
z-index: 3;
}
img {
width: 1.2rem;
}
.icon:hover + .info, .icon:focus + .info {
opacity: 1;
}
`;
// 插进去shadow dom Root
shadow.appendChild(style);
console.log(style.isConnected);
shadow.appendChild(wrapper);
wrapper.appendChild(icon);
wrapper.appendChild(info);
}
}
// 自定义标签
customElements.define('popup-info', PopUpInfo);
</script>
</html>
思索
自定义标签的运用减少了我们频仍编写一堆冗余、深层嵌套的代码,提高了速度。但是,假如我们看页面源码会发明customElements.define不会消弭自定义标签,自定义标签假如绑定了大批的数据、事宜、敏感信息,页面上又完整显示出来,这就增添前端页面的不安全性。怎样保证开发者即运用自定义标签又不会编译自定义标签从而致使DOM的过分挂载和数据的走漏(不发起remove自定义标签,频仍操纵DOM太斲丧内存了),值得思索…