Modernizr 是一個輕量級 JavaScript 庫,專門用於偵測瀏覽器對 HTML5 與 CSS3 特性的支援程度。它不修補功能,而是讓開發者根據偵測結果,編寫條件式 CSS/JS,實現優雅降級或漸進增強。
引入 Modernizr 後,它會在 <html> 標籤上添加一系列類名,例如:
<html class="js flexbox canvas canvastext webgl no-touch geolocation postmessage
websqldatabase indexeddb hashchange history draganddrop websockets rgba hsla
multiplebgs backgroundsize borderimage borderradius boxshadow textshadow
opacity cssanimations csscolumns cssgradients cssreflections csstransforms
csstransforms3d csstransitions fontface generatedcontent video audio localstorage
sessionstorage webworkers applicationcache svg inlinesvg smil svgclippaths">
boxshadow)no- 前綴(如 no-boxshadow)js 類名表示 JavaScript 已啟用(會取代初始的 no-js)/***** 現代瀏覽器:使用 CSS3 陰影 *****/
.boxshadow .card {
box-shadow: 0 4px 20px rgba(0,0,0,0.15);
border: none;
}
/***** 舊版瀏覽器:降級為邊框 *****/
.no-boxshadow .card {
border: 2px solid #ddd;
border-bottom-width: 4px; /* 模擬陰影視覺 */
}
/***** 多重條件組合 *****/
.csstransforms.csstransitions .flip-card:hover .front {
transform: rotateY(180deg);
}
.no-csstransforms3d .flip-card .back { display: none; } /* 隱藏無法翻轉的背面 */
if (Modernizr.canvas) {
// 支援 Canvas:初始化圖表庫
initChart();
} else {
// 不支援:顯示靜態圖片或表格
showFallbackTable();
}
// 同時檢測多項特性
if (Modernizr.video && Modernizr.video.h264) {
// 支援 H.264 影片
}
Modernizr.load([
{
// 條件:需要 WebGL
test: Modernizr.webgl,
// 滿足:載入 Three.js 場景
yep: ["three.min.js", "scene.js"],
// 不滿足:載入 Canvas 版本或靜態圖
nope: ["canvas-fallback.js", "static-scene.jpg"],
// 兩者皆需:分析追蹤
both: ["analytics.js"],
// 載入完成回調
complete: function() { console.log("資源載入完成"); }
},
{
// 另一組條件:表單驗證 + 輸入類型
test: Modernizr.inputtypes.date && Modernizr.formvalidation,
yep: "enhance-forms.js",
nope: ["polyfill/html5forms.js", "polyfill/css3-ui.css"]
}
]);
| CSS 特性 | Modernizr 類名 | JS 屬性 |
|---|---|---|
| @font-face | fontface / no-fontface | Modernizr.fontface |
| border-radius | borderradius / no-borderradius | Modernizr.borderradius |
| box-shadow | boxshadow / no-boxshadow | Modernizr.boxshadow |
| rgba() | rgba / no-rgba | Modernizr.rgba |
| CSS Animations | cssanimations / no-cssanimations | Modernizr.cssanimations |
| CSS Transforms 2D | csstransforms / no-csstransforms | Modernizr.csstransforms |
| CSS Transforms 3D | csstransforms3d / no-csstransforms3d | Modernizr.csstransforms3d |
| CSS Transitions | csstransitions / no-csstransitions | Modernizr.csstransitions |
| Flexbox | flexbox / no-flexbox | Modernizr.flexbox |
| Gradients | cssgradients / no-cssgradients | Modernizr.cssgradients |
| Multiple Backgrounds | multiplebgs / no-multiplebgs | Modernizr.multiplebgs |
| 特性 | JS 屬性 | 備註 |
|---|---|---|
| Canvas | Modernizr.canvas | 含 canvastext 文字繪製 |
| Video / Audio | Modernizr.video / .audio | 子屬性:.h264, .webm, .ogg |
| LocalStorage | Modernizr.localstorage | 同步儲存 |
| SessionStorage | Modernizr.sessionstorage | 會話儲存 |
| Web Workers | Modernizr.webworkers | 多執行緒 |
| Geolocation | Modernizr.geolocation | 需 HTTPS |
| Input Types | Modernizr.inputtypes.date 等 | date, email, number, range, color... |
| Form Validation | Modernizr.formvalidation | Constraint Validation API |
官網 下載頁面 提供模組化勾選,僅打包專案需要的測試,減少檔案體積(核心約 7KB gzip)。
Modernizr.load:若不需條件載入,可排除 yepnope 進一步減量<script src="modernizr-custom.js" async></script> 避免阻塞渲染Modernizr 本身不包含 Polyfill,但配合條件載入可按需引入:
Modernizr.load({
test: Modernizr.fetch,
nope: "polyfill/fetch.min.js", // 只有不支援 fetch 才載入
complete: function() {
// 此時 window.fetch 一定可用
initApiClient();
}
});
常用 Polyfill 來源:polyfill.io(自動根據 User-Agent 返回所需補丁)、polyfill-service。
| 場景 | 現代替代方案 |
|---|---|
| CSS 特性查詢 | @supports (display: grid) { ... } 原生 CSS 條件規則 |
| JS 特性檢測 | 'fetch' in window、CSS.supports()、HTMLInputElement.prototype.reportValidity |
| 條件載入 | 動態 import()、Webpack Code Splitting、<script type="module"> |
| Polyfill 管理 | @babel/preset-env + core-js、polyfill.io |
Modernizr 曾是跨瀏覽器開發的基石,隨著瀏覽器標準化與原生 API 普及,其核心價值已轉移至舊專案維護與極端兼容需求。新專案建議採用 @supports、原生特性檢測與現代建構工具鏈,僅在必須支援 IE11 或舊版行動瀏覽器時才引入 Modernizr。