面對瀏覽器對 HTML5/CSS3 特性支援度參差不齊的現實,**特性偵測** 遠優於「瀏覽器嗅探」。本文詳細說明原生偵測寫法、業界標準庫 **Modernizr** 的深度應用(含自訂建置、載入機制、CSS/JS 雙向整合),並提供**零依賴原生替代方案**,滿足不同專案需求。
// 1. 元素/屬性存在性檢測
const supportsCanvas = 'getContext' in document.createElement('canvas');
const supportsWebGL = 'WebGLRenderingContext' in window;
// 2. CSS 屬性檢測 (需含前綴)
const testEl = document.createElement('div');
const supportsFlex = 'flex' in testEl.style || 'webkitFlex' in testEl.style;
const supportsGrid = 'grid' in testEl.style || 'msGrid' in testEl.style;
// 3. 事件檢測
const supportsTouch = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
// 4. API 完整性檢測 (如 IndexedDB)
const supportsIndexedDB = 'indexedDB' in window && 'IDBKeyRange' in window;
// 通用工具函式
function supports(prop, el = document.createElement('div')) {
const vendors = ['', 'Webkit', 'Moz', 'ms', 'O'];
return vendors.some(v => (v + (v ? prop[0].toUpperCase() + prop.slice(1) : prop)) in el.style);
}
// 用法:supports('transform'), supports('flex'), supports('grid')
flexbox, cssgrid, webgl, webp, fetch, intersectionobserver)。modernizr-custom.js(通常 3~8 KB gzipped),避免完整版 15KB+ 的冗餘。<!DOCTYPE html>
<html class="no-js"> <!-- 預設 no-js,JS 啟用後 Modernizr 會移除 -->
<head>
<meta charset="utf-8">
<script>/*! modernizr-custom.js 內容內嵌或外部引用 */</script>
<link rel="stylesheet" href="styles.css">
</head>
no-js class 讓無 JS 環境也能有基本樣式。<html> 加上 js、flexbox/no-flexbox、webgl/no-webgl 等 class。.container {
display: block; /* fallback */
}
.flexbox .container {
display: flex; /* 支援 flex 時覆寫 */
}
.no-flexbox .container {
display: table; /* 不支援 flex 時的替代佈局 */
}
/* 圖片格式回退 */
.hero { background-image: url('hero.jpg'); }
.webp .hero { background-image: url('hero.webp'); }
.avif .hero { background-image: url('hero.avif'); }
if (Modernizr.canvas) {
initCanvasApp();
} else {
loadPolyfillOrFallback();
}
// 進階:條件載入 (需包含 Modernizr.load / yepnope)
Modernizr.load({
test: Modernizr.webgl,
yep: ['three.min.js', 'app-3d.js'],
nope: ['fallback-2d.js'],
complete: () => console.log('3D/2D module loaded')
});
若不想阻塞渲染,可將 Modernizr 內嵌在 <head> 並加 async,但需配合 **CSS 避免 FOUC 技巧**(如關鍵 CSS 內嵌、body { opacity: 0 } JS 就緒後恢復)。一般建議**同步內嵌精簡版**,體積極小且阻塞時間可忽略。
若專案極度精簡、不想引入任何庫,可自行封裝核心偵測:
// feature-detect.js (約 1KB gzipped)
const Feature = {
_cache: {},
detect(name, fn) {
if (name in this._cache) return this._cache[name];
return this._cache[name] = !!fn();
},
// 內建常用偵測
canvas: () => 'getContext' in document.createElement('canvas'),
webgl: () => 'WebGLRenderingContext' in window,
webgl2: () => 'WebGL2RenderingContext' in window,
flexbox: () => 'flex' in document.documentElement.style || 'webkitFlex' in document.documentElement.style,
grid: () => 'grid' in document.documentElement.style || 'msGrid' in document.documentElement.style,
webp: () => {
const img = new Image();
img.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';
return new Promise(r => { img.onload = img.onerror = () => r(img.height === 1); });
},
// 異步偵測範例
async detectAsync(name) {
const fn = this[name];
if (typeof fn !== 'function') return false;
const result = await fn();
this._cache[name] = result;
return result;
},
// 在 html 加上 class
applyClasses() {
Object.keys(this._cache).forEach(k => {
document.documentElement.classList.toggle(k, this._cache[k]);
document.documentElement.classList.toggle('no-' + k, !this._cache[k]);
});
}
};
// 用法
if (Feature.detect('canvas')) initCanvas();
Feature.detectAsync('webp').then(supported => {
if (supported) document.documentElement.classList.add('webp');
Feature.applyClasses();
});
| 維度 | Modernizr (自訂建置) | 原生自製模組 |
|---|---|---|
| 體積 | 3~8 KB | < 1 KB |
| 偵測項目豐富度 | 200+ 可選 | 自行維護,約 10~20 核心項 |
| 條件載入 (yepnope) | 內建 | 需自行實作 (動態 import) |
| CSS class 自動注入 | 自動 | 需呼叫 applyClasses() |
| 維護成本 | 低 (官方維護) | 自行維護 |
| 適用專案 | 中大型、需大量偵測、條件載入 | 極簡專案、PWA、微前端片段、嵌入式 Widget |
@supports (CSS) 與動態 import() (JS)**:/* CSS 原生特性查詢 */
@supports (display: grid) {
.layout { display: grid; }
}
/* JS 動態載入 */
if ('IntersectionObserver' in window) {
import('./lazy-load.js').then(m => m.init());
} else {
import('./lazy-load-fallback.js').then(m => m.init());
}
navigator.userAgent),永遠以特性存在性為準。