萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 中使用 JavaScript 偵測瀏覽器版本:特性偵測優於瀏覽器嗅探

反模式:User Agent 嗅探

早期常見做法解析 navigator.userAgent 字串判斷瀏覽器,但極不可靠:

  • UA 字串可偽造、格式無標準、新瀏覽器持續變化
  • 維護成本極高,極易誤判
  • 違背漸進增強原則

歷史碼參考(僅供理解舊專案)

// 已棄用:UA 嗅探範例
if (window.XMLHttpRequest) {
  // Mozilla, Safari, IE7+
  if (!window.ActiveXObject) {
    // Firefox, Safari, Chrome, Edge
  } else {
    // IE7+
  }
} else {
  // IE6 及以下
}

現代最佳實踐:特性偵測

檢測瀏覽器「是否支援某功能」而非「是哪個瀏覽器」。

CSS 原生特性查詢

/* 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; }
}

JavaScript 特性偵測

// 檢測 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');
}

專用偵測庫

  • Modernizr:完整特性偵測庫,生成 .flexbox、.no-grid 等 class 掛在 <html>
  • Browserslist + core-js:根據目標瀏覽器自動注入最小 Polyfill

極少數需 UA 的場景

  1. 統計分析(非功能判斷)
  2. 已知特定瀏覽器 Bug 無法特性偵測時的最後手段
  3. 使用 bowser、ua-parser-js 等成熟庫而非手寫正則

CSS Hack 現代替代

/* ❌ 避免:針對瀏覽器的 Hack */
* html .box { }  /* IE6 */
*+html .box { }  /* IE7 */

/* ✅ 推薦:特性查詢 + 漸進增強 */
.box { display: block; }  /* 基礎樣式 */
@supports (display: flex) {
  .box { display: flex; }  /* 現代瀏覽器增強 */
}
copyright © 萬盛學電腦網 all rights reserved