前言
Web Component不是新東西,幾年前的技術,但是受限於瀏覽器兼容性,一直沒有大規模應用在項目里,直到現在(2018年年末),除IE仍不支持之外,其它主流瀏覽器都支持Web Component。
Web Component不是一個東西,它分為四部分,分別是
template——模板
HTML import——HTML導入
Shadow DOM——影子DOM
Custom Elements——自定義元素
template
前端模板也不是個新概念,templatejs、ejs等模板引擎早就將模板的概念深入人心,在純HTML世界里,我們通常把模板寫在script標簽里,將type改為text/html,避免瀏覽器解析,像這樣
<script type="text/html">
<div>
<title>標題</title>
<content>內容</content>
</div>
</script>
template則是用 標簽包裹模板內容,不同之處在於獲取模板內容的方式,script模板是通過獲取script的innerHTML來獲取,template則是獲取讀取template節點的content屬性來獲取
// 模板文件
<template>
<div>
<title>標題</title>
<content>內容</content>
</div>
</template>
// 獲取模板內容
console.log(document.querySelector('template').content);
HTML import
在此之前,HTML導入一般用iframe嵌套或依賴后端又或是其他庫,HTML import為原生HTML提供了導入HTML文件的功能,使用link標簽,rel設置為import,href為被導入文件路徑
<link rel="import" href="header.html">
HTML導入之后不會立即被瀏覽器解析並渲染,需要手動插入到DOM節點,這點跟css不同
// header.html
<h2 id="header">這是公共header</h2>
<h2 id="footer">這是公共footer</h2>
// index.html
<html>
<head>
<link rel="import" href="header.html">
</head>
<body>
<content>內容區</content>
<script type="text/javascript">
let importDom = document.querySelector('link[href="header.html"]').import;
let content = document.querySelector('content');
let header = importDom.querySelector('#header');
let footer = importDom.querySelector('#footer');
document.body.insertBefore(header, content);
document.body.appendChild(footer);
</script>
</body>
</html>
最終渲染結果
這是公共header
內容區