Web Components 的一些入门知识
是一个Web组件标准。Web Components通过一种标准化的非侵入的方式封装一个组件,每个组件能组织好它自身的HTML、CSS、JavaScript,并且不会干扰页面上的其他代码。
包括以下四种技术(每种都可以被单独使用)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<template>
<style>
.com {
font-size: 20px;
}
</style>
<div class="com">my component</div>
</template>
<body>
<my-view></my-view>
<script>
(function () {
// Creates an object based in the HTML Element prototype
// 基于HTML Element prototype 创建obj
var element = Object.create(HTMLElement.prototype);
// 获取特mplate的内容
var template = document.currentScript.ownerDocument.querySelector(
'template'
).content;
// element创建完成之后的回调
element.createdCallback = function () {
// 创建 shadow root
var shadowRoot = this.createShadowRoot();
// 向root中加入模板
var clone = document.importNode(template, true);
shadowRoot.appendChild(clone);
};
document.registerElement('my-view', {
prototype: element,
});
})();
</script>
</body>
</html>