動態載入 CSS 時,需知道何時載入完成以執行後續邏輯(如初始化依賴樣式的組件)。各瀏覽器對 `` 的 `onload` 事件支援度不一,需組合多種策略。
| 瀏覽器 | link.onload | link.onerror | 備註 |
|---|---|---|---|
| IE 6-9 | ✅ 支援 | ❌ | 404 也會觸發 onload |
| IE 10-11 | ✅ | ✅ | |
| Edge (Legacy) | ✅ | ✅ | |
| Firefox | ✅ | ✅ | 需輪詢 sheet.cssRules 確認 |
| Chrome / Safari (WebKit) | ✅ (新版) | ✅ | 舊版需輪詢 sheet 存在性 |
| Opera (Presto) | ❌ | ❌ | 需輪詢 |
function loadCSS(href, callback) {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = href;
document.head.appendChild(link);
let called = false;
function done() {
if (called) return;
called = true;
callback && callback();
}
// 1. 標準 onload(現代瀏覽器)
link.onload = done;
// 2. IE 舊版輪詢 cssRules
let pollTimer;
function poll() {
if (called) return;
try {
// Firefox/IE: sheet.cssRules 存在即載入完成
// WebKit: sheet 存在即可
if (link.sheet && (link.sheet.cssRules || link.sheet.rules)) {
done();
return;
}
} catch (e) {
// Firefox 跨域會拋 NS_ERROR_DOM_SECURITY_ERR (code 1000),視為載入完成
if (e.code === 1000) { done(); return; }
}
pollTimer = setTimeout(poll, 20);
}
// 3. 啟動輪詢(針對不支援 onload 或 onload 不可靠的瀏覽器)
if (!('onload' in link) || /webkit/i.test(navigator.userAgent)) {
pollTimer = setTimeout(poll, 0);
}
// 4. 超時保底
setTimeout(() => { clearTimeout(pollTimer); done(); }, 10000);
return link;
}
loadCSS('/css/theme.css', () => {
console.log('樣式已就緒,初始化 UI 組件');
initComponents();
});
`link.onerror` 在大多數現代瀏覽器支援,可補充:
link.onerror = () => {
console.error('CSS 載入失敗:', href);
// 降級:內聯關鍵樣式、顯示錯誤提示、重試
};
mini-css-extract-plugin 抽離 CSS,配合 link rel="preload"。media="print" onload="this.media='all'" 技巧)。動態載入 CSS 並監聽完成,是微前端、主題切換、按需載入的基礎設施,掌握跨瀏覽器兼容細節至關重要。