構建可復用 UI 組件時,往往需要同時引入 HTML 模板、CSS 樣式、JS 邏輯、Web Fonts 等多種資源。傳統方式需在主頁面手動添加多個 <link>/<script>,極易出現:依賴重複、加載順序錯誤、版本衝突、網絡請求數過多等問題。
HTML Imports(Web Components 四大標準之一)提供原生解決方案:單一 HTML 文件打包所有依賴,一行代碼引入。
<!-- index.html 主頁面 -->
<link rel="import" href="components/x-component.html">
<!-- x-component.html 導入文件 -->
<link rel="stylesheet" href="css/style.css">
<script src="js/script.js"></script>
<template id="tpl"><div>...</div></template>
• 無需 <html>/<body> 等結構標籤;
• 導入文件中的腳本**默認 defer 執行**(不阻塞主文檔解析);
• 支援巢狀導入,瀏覽器自動去重(同一 URL 僅加載執行一次)。
<!-- index.html -->
<link rel="import" href="comp.html"> <!-- 1. 開始加載 comp.html -->
<script src="main.js"></script> <!-- 4. 最後執行 -->
<!-- comp.html -->
<script src="a.js"></script> <-- 2. 先執行 -->
<script src="b.js"></script> <-- 3. 再執行 -->
類似 <script defer>,保證導入文檔內腳本按順序執行完畢,再繼續主文檔後續腳本。
<link rel="import" href="comp.html" async>
標記 async 後,導入不阻塞主文檔渲染,但**不保證執行順序**,若主文檔腳本依賴導入內容,需監聽 load 事件:
const link = document.querySelector('link[rel="import"]');
link.addEventListener('load', e => {
const importedDoc = link.import; // 獲取導入文檔的 Document 對象
// 安全使用導入內容
});
HTML Imports 受同源策略限制。跨域導入需服務端配置 Access-Control-Allow-Origin,且導入文檔腳本執行上下文仍屬主文檔源。
導入文檔腳本中的 document 指向**主文檔**。訪問導入文檔自身 DOM 需用:
// 在導入文檔腳本中
const importedDoc = document.currentScript.ownerDocument;
// 或兼容寫法
const importedDoc = document._currentScript?.ownerDocument || document.currentScript.ownerDocument;
多個組件共用 jQuery 等庫,若各自導入則產生重複請求與執行。HTML Imports 原生去重解決「重複執行」,但**無法合並網絡請求**。
# 安裝
npm install -g vulcanize
# 合並 index.html 及其所有導入依賴
vulcanize -o build/vulcanized.html index.html
產出單一 vulcanized.html,包含所有模板、樣式、腳本,內聯化資源,極大減少 HTTP 請求數。構建流程可整合至 Gulp/Grunt/Webpack。
<!-- x-component.html -->
<template id="tpl">
<style> /* Shadow DOM 隔離樣式 */ :host { display: block; } </style>
<div id="container">
<img src="logo.svg">
<content select="h1"></content> <!-- 內容分發 -->
</div>
</template>
<script>
// 註冊到主文檔(document 指向主文檔)
const XComponent = document.registerElement('x-component', {
prototype: Object.create(HTMLElement.prototype, {
createdCallback: { value: function() {
const tpl = document.querySelector('#tpl'); // 主文檔中查找
const clone = document.importNode(tpl.content, true);
this.createShadowRoot().appendChild(clone);
}}
})
});
</script>
⚠️ HTML Imports 已被 Chrome 移除(v73+),Firefox/Safari 未實現,Web Components 標準轉向 ES Modules + <script type="module">。
現代替代方案:
import './component.js' 靜態分析、樹搖、瀏覽器原生支援;import template from './component.html' 直接導入 HTML 作為模塊;html-loader/vite-plugin-html 實現開發時熱更新、生產時合並內聯;HTML Imports 曾是 Web Components 模組化的關鍵拼圖,雖已退出歷史舞台,但其「單文件組件、依賴去重、聲明式導入」的設計思想,深刻影響了現代前端工程化工具鏈的演進。理解它,有助於把握組件化架構的本質。