Template、Shadow DOM 與 Custom Elements 讓建立 UI 元件變得容易許多,但資源本身還是要一個一個載入。想引入 jQuery UI 或 Bootstrap,得分別為 JavaScript、CSS、Web Fonts 各寫標籤;元件依賴一多,head 就迅速失控。HTML Imports 想解決的正是這件事。
寫法很直觀:一個 link 標籤,rel 設為 import,href 指向要引入的 HTML 檔。若要在 index.html 中載入 component.html:
<link rel="import" href="component.html">
被引入的檔案裡可以放任何資源,寫法跟普通 HTML 一模一樣:
<link rel="stylesheet" href="css/style.css"> <script src="js/script.js"></script>
doctype、html、head、body 這些外框都不需要。瀏覽器會立即載入被引入的文件、解析其中的資源,遇到 script 就執行。
瀏覽器解析 HTML 是線性的:上面的 script 會比下面的先跑,而且通常會等這段 JavaScript 執行完,才繼續往下解析。為了不讓 script 阻擋渲染,一般會加上 async 或 defer——defer 會延後到整份文件解析完才執行,async 則是抓到就非同步執行。
HTML Imports 裡的 script,行為等同帶了 defer。以下面結構為例,執行順序是 script1 → script2 → script3:
<link rel="import" href="component.html"> // 1 <title>Import Example</title> <script src="script3.js"></script> // 4
<script src="js/script1.js"></script> // 2 <script src="js/script2.js"></script> // 3
如果幫 link[rel="import"] 加上 async,它就會被當成帶 async 的 script 對待:主文件不再等待它載入與執行,也就不會被它阻擋渲染。這是提升首屏效能的一個切入點——前提是你沒有其他程式依賴它的執行結果。
基於安全性,HTML Imports 預設不能跨網域引入資源。你不能從 webcomponents.org 引入 HTML 到 example.com。繞過的方式是 CORS(跨來源資源共享),需要由被引入方在回應標頭中明確允許。
這是最容易踩到的一點。被引入檔案中的 script 雖然會執行,但其中的 document 指向的是主文件的 document,而不是自己那份。也就是說,component.html 裡寫 document,拿到的是 index.html 的 document。
要取得被引入文件自己的 document,從主文件這邊透過 link 的 import 屬性:
var link = document.querySelector('link[rel="import"]');
link.addEventListener('load', function(e) {
var importedDoc = link.import; // 指向 component.html 的 document
});
從被引入檔案內部則用 currentScript 的 ownerDocument:
var mainDoc = document.currentScript.ownerDocument; // 指向 component.html 的 document
若使用 webcomponents.js 這套 polyfill,要改寫成 document._currentScript。可以在 script 開頭放一行相容寫法,兩邊都能跑:
document._currentScript = document._currentScript || document.currentScript;
HTML Imports 讓資源得以組織,代價是檔案數量變多、請求數上升。有兩件事值得注意。
如果 index.html 引入 component1.html 與 component2.html,而兩者都各自載入了 jQuery,一般的 script 標籤會讓 jQuery 被下載並執行兩次。HTML Imports 不會:同一份文件已經載入過,就不會重複載入與執行。把 jQuery 包成一個獨立的 import 檔,就只會跑一次。
但檔案數膨脹的問題還在。vulcanize 這個工具能把多份 HTML 依賴解析後合併成一份,大幅減少網路連線數。可以透過 npm 安裝、用命令列執行,也可以掛進 grunt / gulp 的建置流程:
$ vulcanize -o vulcanized.html index.html
執行後會得到一份合併過的 vulcanized.html。當年也預期 HTTP/2 的伺服器推送能在未來某種程度上取代這種連結與合併的手工工。
這幾項技術各自的角色是:Template 讓你用宣告式的方式定義元件內容;Shadow DOM 把樣式、id、class 的作用範圍關在元件之內;Custom Elements 讓你能自訂 HTML 標籤。疊上 HTML Imports 之後,元件就成了模組——別人只要加一行 link 標籤就能用。
<template id="template">
<style> ... </style>
<div id="container">
<img src="https://webcomponents.org/img/logo.svg">
<content select="h1"></content>
</div>
</template>
<script>
// 這裡的 document 就是 index.html 的 document,
// 所以元件會註冊到主文件上
var XComponent = document.registerElement('x-component', {
prototype: Object.create(HTMLElement.prototype, {
createdCallback: {
value: function() {
var root = this.createShadowRoot();
var template = document.querySelector('#template');
var clone = document.importNode(template.content, true);
root.appendChild(clone);
}
}
})
});
</script>
主文件只要引入再使用即可,不需要寫任何額外的綁定程式:
<link rel="import" href="x-component.html"> <x-component> <h1>This is Custom Element</h1> </x-component>
當年 Chrome 與 Opera 提供支援,Firefox 則表示要等先釐清 ES6 模組的做法再說;查詢支援度可到 chromestatus.com 或 caniuse.com,要在其他瀏覽器上使用則需 webcomponents.js(原名 platform.js)這類 polyfill。
補充一點後續發展:HTML Imports 最終並沒有成為跨瀏覽器的標準,規格已被放棄,Chrome 也在後續版本中移除了實作,整個方向被 ES Modules(import / export)取代。今天回頭看,它想解決的問題依然真實——元件化之後如何有秩序地打包與載入資源——只是答案換成了模組系統搭配打包工具。理解它「用一份 HTML 描述一個元件的所有依賴」這個想法,仍有助於掌握 Web Components 的設計脈絡。