Template、Shadow DOM 與 Custom Elements 讓建立 UI 元件變得容易許多,但 HTML、CSS、JavaScript 這些資源仍然只能一個標籤一個標籤地引入,效率並不理想。
去重依賴更麻煩。想載入 jQuery UI 或 Bootstrap,你得分別為 JavaScript、CSS 甚至 Web Fonts 各寫一組標籤;一旦 Web 元件依賴了好幾層,結構會迅速失控。
HTML Imports 的思路很直接:用一個 HTML 檔把這些資源全部打包帶進來。
在主要頁面加一個 link 標籤,rel 設為 import,href 指向要引入的 HTML:
<!-- index.html -->
<link rel="import" href="component.html">
被引入的檔案(component.html)裡可以放任何資源,寫法跟普通 HTML 完全一樣:
<link rel="stylesheet" href="css/style.css">
<script src="js/script.js"></script>
不需要 doctype、html、head、body 這些外殼標籤。瀏覽器會立即載入被引入的檔案、解析其中的資源,並執行裡面的腳本。
瀏覽器解析 HTML 是線性的:上方的 script 早於下方執行,而且通常會等腳本跑完才繼續往下解析。為了不讓腳本阻塞渲染,我們有 async 與 defer 兩個屬性——defer 會把執行時機延後到整份文件解析完畢,async 則讓腳本完全獨立執行。HTML Imports 的行為等同於 defer。
<!-- index.html -->
<link rel="import" href="component.html"> // 1.
<title>Import Example</title>
<script src="script3.js"></script> // 4.
<!-- component.html -->
<script src="js/script1.js"></script> // 2.
<script src="js/script2.js"></script> // 3.
執行流程是:載入 component.html 並等待完成 → 執行 script1.js → 執行 script2.js → 回到主文件執行 script3.js。
如果你在 link[rel="import"] 上加 async,它就被當成 async 腳本對待:不等待載入與執行完成,因此不會阻擋主文件渲染。這是改善首屏效能的一個切入點,前提是有沒有其他腳本依賴它的執行結果。
HTML Imports 預設不能跨網域引入資源。你不能從 webcomponents.org 把檔案匯入 example.com。要繞過這個限制,得靠 CORS(跨來源資源共享)配合伺服器端設定。
這是最容易踩的坑。前面說過被引入檔案中的腳本會被執行,但這不代表它的標籤會被渲染——那需要你自己寫 JS 去搬。更關鍵的是:被引入檔案裡的 document 實際上指向主文件的 document。也就是說 component.html 中的 document 和 index.html 中的是同一個物件。
要拿到被引入檔案自己的 document,得透過 link 元素的 import 屬性:
var link = document.querySelector('link[rel="import"]');
link.addEventListener('load', function(e) {
var importedDoc = link.import; // 指向 component.html 的 document
});
而在 component.html 內部,則用:
var mainDoc = document.currentScript.ownerDocument;
// mainDoc 指向 component.html 的 document
若使用 webcomponents.js polyfill,要改寫成 document._currentScript(底線是為了填補不支援 currentScript 的瀏覽器)。想寫成與瀏覽器無關的通用寫法,在腳本開頭加一行即可:
document._currentScript = document._currentScript || document.currentScript;
HTML Imports 讓資源得以模組化組織,代價是引入了額外的檔案請求,HTML 的 head 可能因此變得冗長。有兩件事需要處理。
如果主文件引入了兩個元件,而兩者都各自載入 jQuery,會發生什麼?
<!-- index.html -->
<link rel="import" href="component1.html">
<link rel="import" href="component2.html">
<!-- component1.html -->
<script src="js/jquery.js"></script>
好消息是 HTML Imports 會自動去重:同一個 HTML 檔不會被載入與執行第二次。把 jQuery 的 script 標籤收進一個 import 檔裡,它就只會被載入一次。
但檔案數量增加了,怎麼辦?答案是 vulcanize 這個工具。它能解析依賴並把多個 HTML 檔合併成一個,大幅減少網路連線數:
$ npm install -g vulcanize
$ vulcanize -o vulcanized.html index.html
執行後會產生合併版 vulcanized.html。如果你已經在用 Grunt 或 Gulp,把它掛進建置流程即可。(補充:HTTP/2 的伺服器推送被視為未來取代合併/拼接的方案。)
Template 讓你用宣告式語法定義元件內容,Shadow DOM 讓樣式、ID、class 的作用範圍侷限在元件內部,自定義元素則讓你能註冊自己的 HTML 標籤。三者加上 HTML Imports,就能產出真正可複用的 Web 元件——使用者只需加一行 link。
<!-- x-component.html -->
<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>
<!-- index.html -->
<link rel="import" href="x-component.html">
</head>
<body>
<x-component>
<h1>This is Custom Element</h1>
</x-component>
因為元件檔中的 document 與主文件相同,註冊會自動生效,不必寫任何額外的銜接程式碼。
Chrome 與 Opera 原生支援 HTML Imports。Firefox 方面 Mozilla 當時表示要先釐清 ES6 模組的實作方式,短期內不打算支援。可以上 chromestatus.com 或 caniuse.com 查詢最新狀況;若要在其他瀏覽器上使用,需要引入 webcomponents.js(原名 platform.js)作為 polyfill。