前端組件化的痛點
在前端組件化橫行的今天,確實極大的提升了開發效率。不過有一個問題不得不被重視,擬引入的這些html、css、js代碼有可能對你的其他代碼造成影響。
雖然我們可以通過命名空間、閉包等一系列措施來加以防備,不過還是存在這些隱患。為了解決這些問題,有一個基本大家遺忘的技術還是可以了解一下的,
那就是Web Components。
Web Components 是什么
Web Components是一個瀏覽器的新功能,提供了一個面向web包括下面幾個方面標准的組件模型。
你可以認為Web Components是一個可復用的用戶接口部件,
屬於瀏覽器的一部分,所以不需要一些額外的例如jQuery或者Dojo之類的工具庫。
一個存在的Web Components的使用完全不需要寫代碼,
僅僅需要在HTML中加一個import 語句就可以了。
Web Components使用了一些新穎並且在開發中的瀏覽器功能。
上面提到的部分當前在瀏覽器中可以正常的運行,但是有好多Web Components可以用來創造的部分沒有被提及。
使用Web Components 你幾乎可以來做任何可以使用HTML,CSS,JS能做到的事情,並且可以更便捷的被復用。
有時候關於Web Components和谷歌的plymer之間可能會存在一些困惑
簡介而論,Polymer是基於Web Components技術的一個框架,你當然可以在不適用其的情況下開發Web Components
Web Components瀏覽器支持性
Web Components並沒有被所有瀏覽器來實現(截止2017年chrome已經完全支持,其他瀏覽器還在投票表決中),因此如果在不支持的瀏覽器上使用Web Components,
應該使用由google polymer開發的 polyfills來達到目的。使用之前最好通過Are We Componentized Yet查看瀏覽器兼容性。
Web Components 包括以下四種技術(每種都可以被單獨使用)
-
Shadow DOM
明確的定義如下:
一種可以在document下組合多個同級別並且可以項目作用的DOM樹的方法,因此可以更好完善DOM的構成 -
Custom Elements
定義如下:
一種可以允許開發者在document中定義並使用的新的dom元素類型,即自定義元素 -
HTML Templates
模板沒什么可說了,在標准實現之前其實我們一直都在用js來實現該方式 -
HTML Imports
一種允許一個html文檔在別的htmldocuments中包含和復用的方法
明確的文檔定義如下:
- 一種新的html元素: template
- 關於 template 的接口: HTMLTemplateElement, HTMLContentElement (removed from spec) and HTMLShadowElement
- HTMLLinkElement接口和 link 元素的擴展
- 注冊custom elements的接口:Document.registerElement()和對Document.createElement() and Document.createElementNS()的更新
- 對html元素原型對象新增的生命周期回調
- 默認為元素對象增加的新的css的偽類::unresolved
- The Shadow DOM:ShadowRoot and Element.createShadowRoot(), Element.getDestinationInsertionPoints(), Element.shadowRoot
- Event接口的擴展、Event.path
- Document 接口的一些擴展
- Web Components樣式應用新的偽類::host, :host(), :host-context()
如何使用
接下看最直接的還是hello world 。直接上代碼:
index.html
<!DOCTYPE>
<html>
<head>
<title>webcomponent</title>
<link rel="import" href="./components/helloword.html" />
</head>
<body>
<hellow-world></hellow-world>
</body>
</html>
helloworld.html
<template>
<style>
.coloured {
color: red;
}
</style>
<p>the first webcompnent is <strong class="coloured">Hello World</strong></p>
</template>
<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('hellow-world', {
prototype: element
});
}());
</script>
運行結果
結束語
上面就是關於WebComponents的基本介紹了,更多請移步webcomponent-demo查看。
作為一個目前都沒有被瀏覽器全部支持的技術,當然是不會被大面積推廣開來的。不過它的出現還是對組件的問題帶來了一定的積極影響,
假以時日,也許會被所有瀏覽器全面支持,成為我們常用的一種方法。
