# Nginx
location ~* \.(eot|ttf|woff|woff2)$ {
add_header Access-Control-Allow-Origin *;
add_header Cache-Control "public, max-age=31536000, immutable";
}
# Apache
Header set Access-Control-Allow-Origin "*"
Header set Cache-Control "public, max-age=31536000, immutable"
<link rel="preload" as="font" type="font/woff2" crossorigin href="/fonts/MyFont.woff2">
<link rel="stylesheet" href="/fonts/fonts.css" media="print" onload="this.media='all'">
<noscript><link rel="stylesheet" href="/fonts/fonts.css"></noscript>
preload:最高優先級下載字體檔案,crossorigin 必加。media="print":瀏覽器低優先級下載 CSS,**不阻塞渲染**。onload:下載完成切換為 media="all" 套用樣式。noscript:JS 關閉時的回退。| 值 | 區塊期 | 交換期 | 行為 | 推薦場景 |
|---|---|---|---|---|
block | 3s | ∞ | 先隱藏文字,載入完成再顯示 (FOIT) | 品牌標題、關鍵 UI 字體 |
swap | 0s | ∞ | 立即用備用字體顯示,載入後替換 (FOUT) | **正文、大多數 UI** (推薦預設) |
fallback | 100ms | 3s | 短暫隱藏,超時用備用字體,載入後替換 | 次要裝飾字體 |
optional | 100ms | 0s | 極短嘗試,失敗則永久用備用字體 | 非關鍵裝飾、圖示字體 |
@font-face {
font-family: 'MyFont';
src: url('/fonts/MyFont.woff2') format('woff2');
font-display: swap; /* 關鍵:避免文字隱形 */
}
fonttools (pyftsubset)、glyphhanger、transfonter.org、font-spider (自動分析頁面用字)。font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
@font-face 定義 unicode-range,僅在需要特殊字符時載入 Web Font。<style>
@font-face {
font-family: 'CriticalFont';
src: url(data:font/woff2;base64,...) format('woff2'); /* Base64 內嵌關鍵字體 */
font-display: swap;
}
h1 { font-family: 'CriticalFont', var(--font-fallback); }
</style>
size-adjust 緩解)。document.fonts.ready.then(() => ...) 監控載入完成。字體優化是「千刀萬剮」的系統工程:CDN + Preload + font-display:swap + 子集化 + 系統字體優先 + 關鍵字體內嵌,層層疊加才能達到極致體驗。更多 Web Vitals 優化實戰,請關注本站效能工程專欄。