早期常見做法解析 navigator.userAgent 字串判斷瀏覽器,但極不可靠:
// 已棄用:UA 嗅探範例
if (window.XMLHttpRequest) {
// Mozilla, Safari, IE7+
if (!window.ActiveXObject) {
// Firefox, Safari, Chrome, Edge
} else {
// IE7+
}
} else {
// IE6 及以下
}
檢測瀏覽器「是否支援某功能」而非「是哪個瀏覽器」。
/* CSS 原生支援,無需 JS */
@supports (display: grid) {
.container { display: grid; grid-template-columns: 1fr 1fr; }
}
@supports not (display: grid) {
.container { display: flex; } /* 降級方案 */
}
@supports (--css: variables) {
:root { --main-color: #007bff; }
}
// 檢測 CSS 屬性支援
if (CSS.supports('display', 'grid')) {
// 支援 Grid
}
// 檢測 API 存在性
if ('IntersectionObserver' in window) {
// 支援交集觀察器
}
// 檢測屬性/方法
const canvas = document.createElement('canvas');
if (canvas.getContext) {
// 支援 Canvas
}
// 現代化:動態導入 Polyfill
if (!Element.prototype.closest) {
import('element-closest-polyfill');
}
.flexbox、.no-grid 等 class 掛在 <html>bowser、ua-parser-js 等成熟庫而非手寫正則/* ❌ 避免:針對瀏覽器的 Hack */
* html .box { } /* IE6 */
*+html .box { } /* IE7 */
/* ✅ 推薦:特性查詢 + 漸進增強 */
.box { display: block; } /* 基礎樣式 */
@supports (display: flex) {
.box { display: flex; } /* 現代瀏覽器增強 */
}