現代最佳實踐:檢測功能而非瀏覽器身份。但歷史專案中,針對 IE6/7 的 CSS Hack 有時仍需在 JS 層面判斷瀏覽器能力分發樣式。
if (window.XMLHttpRequest) {
// 支援 XMLHttpRequest:現代瀏覽器 + IE7+
alert('Modern browsers or IE7+');
if (!window.ActiveXObject) {
// 無 ActiveXObject:Firefox, Chrome, Safari, Edge...
alert('Non-IE modern browsers');
} else {
// 有 ActiveXObject 且有 XMLHttpRequest:IE7, IE8, IE9, IE10
alert('IE7+');
}
} else {
// 無 XMLHttpRequest:IE6 及以下
alert('IE6 or older');
}
| 問題 | 影響 | 修正 |
|---|---|---|
| IE10+ 同時擁有 XMLHttpRequest 和 ActiveXObject | 被誤判為 IE7+ | 檢測 window.atob 或 document.documentMode |
| 依賴 alert 阻塞執行 | 生產環境不可用 | 改為類名掛載 document.documentElement.classList.add('ie7') |
| 無法區分 IE8/9/10/11 | 精準 Hack 不可能 | 條件註釋 / document.documentMode / User Agent 最後手段 |
@supports (display: grid) {
.layout { display: grid; }
}
@supports not (display: grid) {
.layout { display: flex; } /* 降級 */
}
<!--[if lt IE 9]>
<link rel="stylesheet" href="ie8-fix.css">
<![endif]-->
<!--[if IE 7]>
<link rel="stylesheet" href="ie7-fix.css">
<![endif]-->
(function() {
const html = document.documentElement;
const ua = navigator.userAgent;
// IE 版本檢測(IE11 移除 MSIE 字樣)
const isIE = /MSIE|Trident/.test(ua);
const ieVersion = isIE ? (ua.match(/(?:MSIE |rv:)(\d+)/) || [])[1] : null;
if (ieVersion) {
html.classList.add('ie', 'ie' + ieVersion);
// 同時標記版本範圍
if (ieVersion <= 8) html.classList.add('ie-lte8');
if (ieVersion <= 9) html.classList.add('ie-lte9');
}
// 觸屏檢測
if ('ontouchstart' in window) html.classList.add('touch');
// 高 DPI
if (window.devicePixelRatio > 1.5) html.classList.add('hidpi');
})();
.component { display: grid; }
.ie-lte9 .component { display: flex; } /* IE9 降級 */
.touch .component:hover { /* 觸屏無 hover,移除或替代 */ }
.hidpi .icon { background-image: url(icon@2x.png); }
原文代碼展示了早期「特性檢測推斷瀏覽器」的思路,但邏輯存在漏洞且侵入性強。現代前端應擁抱 @supports 特性查詢 與 漸進增強 理念,將瀏覽器差異處理控制在 CSS 層面,極少數情況下才透過 JS 掛載文檔類名實現精準降級。這才是可維護、可測試、面向未來的專業做法。