前端效能預算實戰:Core Web Vitals優化的6個關鍵策略

性能优化

前端效能痛點:為什麼你的網站越來越慢

2026年,前端專案的複雜度持續攀升。LCP 超標、CLS 抖動、INP 延遲、套件體積膨脹、效能退化無感知——這些問題正在吞噬你的使用者體驗和搜尋引擎排名。

痛點 典型表現 業務影響
LCP 超標 首屏渲染 > 3s 跳出率上升 53%
CLS 抖動 頁面版面偏移 > 0.25 使用者誤點擊,信任度下降
INP 延遲 互動回應 > 500ms 使用者流失率增加 40%
套件體積膨脹 JS > 500KB (gzip) 首次載入時間翻倍
效能退化無感知 上線後分數悄悄下降 問題累積數月才發現

核心概念速查

概念 說明 目標值
效能預算 (Performance Budget) 為效能指標設定的量化閾值 團隊自訂
LCP 最大內容繪製時間 ≤ 2.5s
FID 首次輸入延遲 ≤ 100ms
CLS 累積版面偏移 ≤ 0.1
INP 互動到下次繪製延遲 ≤ 200ms
TTFB 首位元組時間 ≤ 800ms
Lighthouse Google 自動化效能稽核工具 ≥ 90 分
效能監控 (RUM) 真實使用者效能資料採集 P75 達標
套件體積分析 Bundle 組成與大小追蹤 JS ≤ 200KB
程式碼分割 按路由/功能拆分載入單元 首屏 ≤ 100KB

五大挑戰:效能預算為什麼難以落地

1. 效能指標定義不清 — 團隊對「好效能」沒有共識,LCP 用實驗室資料還是欄位資料?P75 還是 P95?

2. 預算執行困難 — 預算定義了但沒有強制手段,PR 合了就合了,超了也沒人管。

3. 第三方指令碼影響 — 分析、廣告、客服外掛貢獻了 40-60% 的 JS 執行時間,但你幾乎無法控制。

4. 行動端效能差異 — 桌面端 Lighthouse 95 分,低階安卓機實測 LCP 6 秒,差距巨大。

5. 效能退化偵測 — 沒有持續監控,效能退化像溫水煮青蛙,等你發現時已經嚴重超標。


策略1:Core Web Vitals 指標採集與分析

使用 web-vitals 函式庫採集真實使用者指標,上報至分析平台:

import { onLCP, onFID, onCLS, onINP, onTTFB } from 'web-vitals';

interface PerformanceMetric {
  name: string;
  value: number;
  rating: 'good' | 'needs-improvement' | 'poor';
  delta: number;
  navigationType: string;
  timestamp: number;
}

function reportMetric(metric: PerformanceMetric): void {
  const body = JSON.stringify({
    name: metric.name,
    value: Math.round(metric.value),
    rating: metric.rating,
    delta: Math.round(metric.delta),
    navigationType: metric.navigationType,
    url: window.location.href,
    timestamp: metric.timestamp,
    userAgent: navigator.userAgent,
    connection: (navigator as any).connection?.effectiveType ?? 'unknown',
  });

  if (navigator.sendBeacon) {
    navigator.sendBeacon('/api/v1/metrics', body);
  } else {
    fetch('/api/v1/metrics', { body, method: 'POST', keepalive: true });
  }
}

onLCP(reportMetric);
onFID(reportMetric);
onCLS(reportMetric);
onINP(reportMetric);
onTTFB(reportMetric);

服務端聚合後按 P75 統計,與預算閾值對比:

const PERFORMANCE_BUDGET: Record<string, { good: number; poor: number }> = {
  LCP:  { good: 2500, poor: 4000 },
  FID:  { good: 100,  poor: 300 },
  CLS:  { good: 0.1,  poor: 0.25 },
  INP:  { good: 200,  poor: 500 },
  TTFB: { good: 800,  poor: 1800 },
};

function evaluateBudget(
  metric: string,
  p75Value: number,
): 'pass' | 'warning' | 'fail' {
  const budget = PERFORMANCE_BUDGET[metric];
  if (!budget) return 'pass';
  if (p75Value <= budget.good) return 'pass';
  if (p75Value <= budget.poor) return 'warning';
  return 'fail';
}

策略2:套件體積預算與 Lighthouse CI 整合

在 CI/CD 流水線中強制執行套件體積和 Lighthouse 分數預算:

// lighthouse-budget.json
const lighthouseBudget = {
  budgets: [
    {
      path: '/*',
      options: {
        firstContentfulPaint: 1800,
        largestContentfulPaint: 2500,
        cumulativeLayoutShift: 0.1,
        totalBlockingTime: 200,
        interactive: 3500,
      },
      resourceSizes: [
        { resourceType: 'script', budget: 200 },
        { resourceType: 'stylesheet', budget: 50 },
        { resourceType: 'image', budget: 300 },
        { resourceType: 'total', budget: 800 },
      ],
      resourceCounts: [
        { resourceType: 'third-party', budget: 5 },
        { resourceType: 'total', budget: 30 },
      ],
    },
  ],
};

export default lighthouseBudget;

GitHub Actions 整合:

# .github/workflows/lighthouse-ci.yml
name: Lighthouse CI
on: [push]
jobs:
  lighthouse:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - run: npm ci && npm run build
      - name: Run Lighthouse CI
        uses: treosh/lighthouse-ci-action@v12
        with:
          configPath: .lighthouserc.json
          budgetPath: lighthouse-budget.json
          uploadArtifacts: true
          failOnBudgetExceeded: true
{
  "ci": {
    "collect": {
      "numberOfRuns": 3,
      "startServerCommand": "npm run preview",
      "url": ["http://localhost:4173/"]
    },
    "assert": {
      "assertions": {
        "categories:performance": ["error", { "minScore": 0.9 }],
        "first-contentful-paint": ["error", { "maxNumericValue": 1800 }],
        "largest-contentful-paint": ["error", { "maxNumericValue": 2500 }],
        "cumulative-layout-shift": ["error", { "maxNumericValue": 0.1 }],
        "total-blocking-time": ["error", { "maxNumericValue": 200 }]
      }
    }
  }
}

策略3:圖片與資源載入最佳化

interface ImageOptimizationConfig {
  maxWidth: number;
  quality: number;
  formats: string[];
  sizes: string;
  lazyThreshold: number;
}

const imageConfig: ImageOptimizationConfig = {
  maxWidth: 1600,
  quality: 80,
  formats: ['avif', 'webp', 'jpg'],
  sizes: '(max-width: 768px) 100vw, (max-width: 1200px) 80vw, 1200px',
  lazyThreshold: 0.1,
};

function generatePictureElement(
  src: string,
  alt: string,
  width: number,
  height: number,
  isLcp: boolean = false,
): string {
  const { formats, sizes, quality } = imageConfig;
  const widths = [400, 800, 1200, 1600];

  const sources = formats
    .filter((f) => f !== 'jpg')
    .map((format) => {
      const srcset = widths
        .map((w) => `${src}?w=${w}&q=${quality}&f=${format} ${w}w`)
        .join(', ');
      return `<source srcset="${srcset}" type="image/${format}" />`;
    })
    .join('\n');

  const imgSrcset = widths
    .map((w) => `${src}?w=${w}&q=${quality} ${w}w`)
    .join(', ');

  const lcpAttrs = isLcp
    ? 'fetchpriority="high" loading="eager"'
    : 'loading="lazy"';

  return `<picture>\n${sources}\n<img src="${src}?w=${width}&q=${quality}" srcset="${imgSrcset}" sizes="${sizes}" alt="${alt}" width="${width}" height="${height}" decoding="async" ${lcpAttrs} />\n</picture>`;
}

function setupResourceHints(): void {
  const preconnectDomains = [
    'https://fonts.googleapis.com',
    'https://cdn.example.com',
  ];
  preconnectDomains.forEach((domain) => {
    const link = document.createElement('link');
    link.rel = 'preconnect';
    link.href = domain;
    link.crossOrigin = 'anonymous';
    document.head.appendChild(link);
  });
}

策略4:程式碼分割與延遲載入策略

import { defineAsyncComponent } from 'vue';

interface ChunkConfig {
  name: string;
  test: (modulePath: string) => boolean;
  priority: number;
  minSize: number;
}

const chunkStrategy: ChunkConfig[] = [
  { name: 'vendor-vue', test: /node_modules\/vue/, priority: 10, minSize: 0 },
  { name: 'vendor-ui', test: /node_modules\/@ui-lib/, priority: 8, minSize: 10000 },
  { name: 'vendor-utils', test: /node_modules\/(lodash|date-fns)/, priority: 5, minSize: 0 },
  { name: 'vendor-other', test: /node_modules/, priority: -10, minSize: 20000 },
];

function buildRollupOutputChunks() {
  const manualChunks = (id: string) => {
    if (!id.includes('node_modules')) return;
    for (const chunk of chunkStrategy) {
      if (chunk.test(id)) return chunk.name;
    }
  };
  return { manualChunks };
}

const LazyChart = defineAsyncComponent({
  loader: () => import('@/components/HeavyChart.vue'),
  loadingComponent: () => null,
  delay: 200,
  timeout: 10000,
});

const LazyEditor = defineAsyncComponent({
  loader: () => import('@/components/RichEditor.vue'),
  loadingComponent: () => null,
  delay: 200,
  timeout: 10000,
});

function setupIntersectionLazyLoad(): void {
  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const el = entry.target as HTMLElement;
          const modulePath = el.dataset.lazyModule;
          if (modulePath) {
            import(/* @vite-ignore */ modulePath).then((mod) => {
              el.dispatchEvent(new CustomEvent('lazy-loaded', { detail: mod }));
            });
            observer.unobserve(el);
          }
        }
      });
    },
    { rootMargin: '200px' },
  );

  document.querySelectorAll('[data-lazy-module]').forEach((el) => {
    observer.observe(el);
  });
}

策略5:第三方指令碼治理

interface ThirdPartyScript {
  name: string;
  src: string;
  category: 'analytics' | 'ads' | 'chat' | 'social' | 'other';
  impact: 'high' | 'medium' | 'low';
  loadStrategy: 'async' | 'defer' | 'lazy' | 'worker';
  condition?: () => boolean;
}

const thirdPartyRegistry: ThirdPartyScript[] = [
  {
    name: 'google-analytics',
    src: 'https://www.googletagmanager.com/gtag/js',
    category: 'analytics',
    impact: 'medium',
    loadStrategy: 'async',
    condition: () => !navigator.doNotTrack,
  },
  {
    name: 'live-chat',
    src: 'https://chat.example.com/widget.js',
    category: 'chat',
    impact: 'high',
    loadStrategy: 'lazy',
    condition: () => window.innerWidth >= 768,
  },
  {
    name: 'ad-network',
    src: 'https://ads.example.com/sdk.js',
    category: 'ads',
    impact: 'high',
    loadStrategy: 'worker',
  },
];

function loadThirdPartyScript(script: ThirdPartyScript): Promise<void> {
  if (script.condition && !script.condition()) {
    return Promise.resolve();
  }

  return new Promise((resolve, reject) => {
    const el = document.createElement('script');
    el.src = script.src;

    switch (script.loadStrategy) {
      case 'async':
        el.async = true;
        document.head.appendChild(el);
        break;
      case 'defer':
        el.defer = true;
        document.head.appendChild(el);
        break;
      case 'lazy':
        setTimeout(() => {
          el.async = true;
          document.head.appendChild(el);
        }, 3000);
        break;
      case 'worker':
        fetch(script.src)
          .then((r) => r.text())
          .then((code) => {
            const blob = new Blob([code], { type: 'application/javascript' });
            const worker = new Worker(URL.createObjectURL(blob));
            worker.postMessage({ type: 'init' });
          })
          .catch(reject);
        break;
    }

    el.onload = () => resolve();
    el.onerror = () => reject(new Error(`Failed to load: ${script.name}`));
  });
}

function initThirdPartyScripts(): void {
  const highPriority = thirdPartyRegistry.filter((s) => s.impact === 'low');
  const lowPriority = thirdPartyRegistry.filter((s) => s.impact !== 'low');

  highPriority.forEach(loadThirdPartyScript);

  if ('requestIdleCallback' in window) {
    requestIdleCallback(() => {
      lowPriority.forEach(loadThirdPartyScript);
    });
  } else {
    setTimeout(() => {
      lowPriority.forEach(loadThirdPartyScript);
    }, 5000);
  }
}

策略6:效能監控與告警系統

interface AlertRule {
  metric: string;
  threshold: number;
  windowMinutes: number;
  sampleSize: number;
  channels: ('email' | 'slack' | 'webhook')[];
}

interface PerformanceAlert {
  metric: string;
  currentValue: number;
  threshold: number;
  affectedUsers: number;
  timestamp: string;
}

const alertRules: AlertRule[] = [
  { metric: 'LCP', threshold: 4000, windowMinutes: 30, sampleSize: 50, channels: ['slack', 'email'] },
  { metric: 'CLS', threshold: 0.25, windowMinutes: 30, sampleSize: 50, channels: ['slack'] },
  { metric: 'INP', threshold: 500, windowMinutes: 60, sampleSize: 100, channels: ['slack', 'email'] },
  { metric: 'TTFB', threshold: 1800, windowMinutes: 30, sampleSize: 50, channels: ['slack'] },
];

class PerformanceMonitor {
  private metricsBuffer: Map<string, number[]> = new Map();

  addMetric(name: string, value: number): void {
    if (!this.metricsBuffer.has(name)) {
      this.metricsBuffer.set(name, []);
    }
    const buffer = this.metricsBuffer.get(name)!;
    buffer.push(value);
    if (buffer.length > 1000) buffer.shift();
    this.checkAlerts(name);
  }

  private checkAlerts(metricName: string): void {
    const rule = alertRules.find((r) => r.metric === metricName);
    if (!rule) return;

    const buffer = this.metricsBuffer.get(metricName) ?? [];
    const recentValues = buffer.slice(-rule.sampleSize);
    if (recentValues.length < rule.sampleSize) return;

    const p75 = this.calculatePercentile(recentValues, 75);
    if (p75 > rule.threshold) {
      this.fireAlert({
        metric: metricName,
        currentValue: p75,
        threshold: rule.threshold,
        affectedUsers: recentValues.length,
        timestamp: new Date().toISOString(),
      });
    }
  }

  private calculatePercentile(values: number[], percentile: number): number {
    const sorted = [...values].sort((a, b) => a - b);
    const index = Math.ceil((percentile / 100) * sorted.length) - 1;
    return sorted[index];
  }

  private fireAlert(alert: PerformanceAlert): void {
    console.warn(`[Performance Alert] ${alert.metric} P75=${alert.currentValue}ms exceeds ${alert.threshold}ms`);
    fetch('/api/v1/alerts', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(alert),
      keepalive: true,
    });
  }
}

const monitor = new PerformanceMonitor();

避坑指南

❌ 錯誤做法 ✅ 正確做法
只看 Lighthouse 實驗室資料 結合 RUM 真實使用者資料,實驗室+欄位雙驗證
效能預算只在文件裡定義 在 CI/CD 中強制執行,failOnBudgetExceeded: true
LCP 圖片使用 lazy loading LCP 元素必須 loading="eager" + fetchpriority="high"
第三方指令碼全部同步載入 按影響分級,低優先順序用 requestIdleCallback 延遲
只最佳化桌面端 以低階行動裝置為基準測試,Moto G Power 等中端機型

報錯排查

錯誤現象 可能原因 解決方案
Lighthouse 分數波動大 網路不穩定、CPU 節流不一致 多次執行取中位數,使用 numberOfRuns: 3
LCP 始終 > 4s 圖片未最佳化或未預載入 使用 AVIF + fetchpriority="high" + preload
CLS > 0.25 圖片/廣告無尺寸宣告 始終設定 width/heightaspect-ratio
INP > 500ms 長任務阻塞主執行緒 拆分長任務,scheduler.yield() 讓出主執行緒
套件體積預算 CI 不生效 budgetPath 路徑錯誤 確認相對路徑正確,檢查 JSON 語法
web-vitals 資料遺失 sendBeacon 在頁面卸載時被取消 使用 fetch + keepalive: true 作為降級
程式碼分割後首屏更慢 過度拆分導致請求瀑布流 合併小 chunk,首屏關鍵路徑內聯
第三方指令碼載入失敗 CSP 策略阻止 Content-Security-Policy 中新增對應網域
TTFB > 1.8s 伺服端渲染慢或 CDN 未命中 啟用邊緣快取,最佳化 SSR 快取策略
字型閃爍 (FOIT/FOUT) 未宣告 font-display 使用 font-display: swap + preload

進階最佳化

  1. 使用 Partytown 將第三方指令碼移至 Web Worker — 將分析指令碼等非關鍵 JS 移出主執行緒,INP 可降低 30-50%。設定 <script type="text/partytown"> 即可。

  2. Speculation Rules 預渲染 — 利用 <script type="speculationrules"> 對使用者可能造訪的頁面進行預渲染,LCP 可降至 0.5s 以內。

  3. 基於 RUM 資料的 A/B 效能實驗 — 將不同最佳化策略應用於不同使用者群,對比 P75 指標差異,用資料驅動決策而非猜測。

  4. Service Worker 串流快取 — 使用 Streams API 實現漸進式快取回應,首屏渲染不阻塞於完整資源下載。


工具對比

維度 Lighthouse WebPageTest SpeedCurve Calibre
定位 自動化稽核 深度網路分析 持續效能監控 團隊協作監控
資料型別 實驗室 (Synthetic) 實驗室 (Synthetic) 實驗室 + RUM 實驗室 + RUM
裝置模擬 有限(Throttling) 豐富(真實裝置) 多地區多裝置 多地區多裝置
CI 整合 優秀(官方 CI) 一般 優秀 優秀
費用 免費 免費額度 付費 付費
適合場景 快速稽核、CI 閘道 深度診斷網路問題 長期趨勢監控 團隊協作與告警

總結與展望

前端效能預算不是一次性任務,而是持續工程實踐。2026年的關鍵趨勢:

  • INP 替代 FID 已成為 Core Web Vitals 正式指標,互動回應成為新焦點
  • 效能預算 CI 化 — 從文件約定走向程式碼強制,failOnBudgetExceeded 是底線
  • RUM 驅動決策 — 實驗室資料只是起點,真實使用者資料才是真相
  • Web Worker 卸載 — Partytown 等方案讓第三方指令碼不再拖累主執行緒

建立效能預算體系,讓你的網站在每次發布時都有「效能安檢」,而非等到使用者投訴才發現問題。


線上工具推薦

本站提供瀏覽器本地工具,免註冊即可試用 →

#性能预算#前端性能优化#Core Web Vitals#Lighthouse#包体积优化#2026#性能优化