Communitygithub.com

Blaise1030/astro-marketing

優化網頁效能,提升載入速度與使用者體驗。當被要求「加快網站速度」、「優化效能」、「減少載入時間」、「修復緩慢載入」、「改善頁面速度」或「效能審核」時使用。

astro-marketing 是什麼?

這個技能提供了一套以證據為導向的網頁效能優化工作流程,專注於真實使用者訊號(CrUX)與瀏覽器追蹤(Performance Trace)的結合,以優先處理並診斷 Core Web Vitals 問題(LCP、INP、CLS)。它支援基於 Chrome DevTools MCP 的 `performance_start_trace` 與 `performance_analyze_insight` 來進行實驗室診斷,並明確建議不要使用 `lighthouse_audit` 進行效能分析。技能涵蓋了關鍵渲染路徑的最佳化(伺服器回應、資源預載、字型載入)、圖片最佳化(AVIF、WebP、picture 元素、延遲載入)、字型最佳化(字體交換、可變字體)、快取策略(Cache-Control、Service Worker)、執行時期效能(避免佈局抖動、防抖、requestAnimationFrame、虛擬列表)以及第三方腳本的載入策略。此外,還整合了 View Transitions API 與規範規則(Speculation Rules)以實現流暢的導航動畫與預渲染。使用時必須先建立「現場+實驗室」的基準測量,僅針對測量到的瓶頸進行修改,並在修改後重新執行實驗室測試回報前後數據。

相容平台✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Blaise1030/astro-marketing/tree/HEAD/.agents/skills/performance

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

預覽

來自技能 README

astro-marketing preview
astro-marketing preview
astro-marketing preview
astro-marketing preview

說明文件

效能優化

以證據為導向的效能優化,使用真實使用者訊號進行優先順序排序,並使用瀏覽器追蹤進行診斷。專注於載入速度、執行階段回應性與資源傳遞。

運作方式

  1. 如果頁面可執行,請先閱讀測量工作流程,並在編輯前建立「現場+實驗室」的基準測量。
  2. 優先處理不佳的真實使用者 Core Web Vitals。使用 DevTools 效能追蹤及其聚焦的洞察來找出原因。
  3. 僅檢查並變更與測量到的瓶頸相關的程式碼或資產。
  4. 重新執行等效的實驗室測量,並回報前/後數值、條件與不確定性。現場驗證將保持待處理,直到累積足夠的新使用者數據。

當沒有可執行的頁面時,執行靜態檢查,但將發現稱為假設,而非測量到的回歸。請包含可以驗證每個高影響力假設的指令或瀏覽器工作流程。

偏好使用能記錄效能追蹤並公開聚焦洞察的瀏覽器工具。在使用 Chrome DevTools MCP 時,請使用 performance_start_trace 與 performance_analyze_insight;不要透過 lighthouse_audit 來處理效能,因為它涵蓋了非效能的 Lighthouse 類別。

起始效能預算

預算必須反映產品的目標裝置、網路、頁面類型與使用者旅程。以下數值是典型內容或商務頁面的初始基準,並非通用的通過/失敗標準。如果專案已有定義的預算,請保留它。

資源預算理由
總頁面權重< 1.5 MB限制在受限目標網路上的傳輸時間與數據成本;使用代表性頁面進行校準
JavaScript (壓縮後)< 300 KB保護解析與執行成本
CSS (壓縮後)< 100 KB限制會封鎖渲染的工作
圖片 (above-fold)< 500 KB保護可能的 LCP 資源
字型< 100 KB限制關鍵字型傳輸
第三方< 200 KB限制產品控制範圍外的程式碼

關鍵渲染路徑

伺服器回應

  • TTFB < 800ms. 第一個位元組的時間應快速。使用 CDN、快取與高效的後端。
  • 啟用壓縮。 對文字資產使用 Gzip 或 Brotli。Brotli 是首選 (小 15-20%)。
  • HTTP/2 或 HTTP/3. 多路複用可減少連線開銷。
  • 邊緣快取。 在可能的情況下,在 CDN 邊緣快取 HTML。
  • 考慮對測量到的文件延遲使用 Early Hints (HTTP 103)。 如果追蹤顯示 HTML 生成緩慢但關鍵子資源穩定,請在相同請求的正常最終回應之前,發送一個包含 Link 標頭的臨時 103 回應。使用 HTTP/2 或更新版本。CDN 可以根據早期 200 回應中的 Link 標頭合成 103,或者原始/邊緣處理器可以直接發出它。不支援的用戶端會繼續到最終回應,但請確認當前瀏覽器與基礎設施的支援。將提示限制在經過驗證的關鍵預載或預連線:不準確的提示會浪費頻寬。Cloudflare 在一個人工的、以圖片為主的測試中報告了 20-30% 的 LCP 改善;請將其視為供應商案例研究,而非預期節省,並測量您的結果。請參閱 MDN 的 103 實作範例 和 Cloudflare 研究。

資源載入

預連線到必要的來源:

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://cdn.example.com" crossorigin>

預載關鍵資源:

僅預載那些在追蹤中可見的、發現時間較晚的資源。每次預載都會競爭頻寬,不必要的優先級請求可能會延遲 LCP。

<!-- LCP 圖片 -->
<link rel="preload" href="/hero.webp" as="image" fetchpriority="high">

<!-- 關鍵字型 -->
<link rel="preload" href="/font.woff2" as="font" type="font/woff2" crossorigin>

使用 Speculation Rules API 預渲染可能的下一個導航:

<script type="speculationrules">
{
  "prerender": [{
    "where": { "href_matches": "/*" },
    "eagerness": "moderate"
  }]
}
</script>

moderate 會比 eager 模式等待更強烈的意圖訊號。請測量預測命中率、傳輸位元組數與伺服器成本;錯誤的預渲染大約等於一次未使用的導航。請參閱 core-web-vitals → LCP 了解權衡取捨以及分析所需的 prerenderingchange 閘門。

延遲非關鍵 CSS:

<!-- 內聯關鍵 CSS -->
<style>/* Above-fold 樣式 */</style>

<!-- 非關鍵 CSS -->
<link rel="preload" href="/styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="/styles.css"></noscript>

JavaScript 最佳化

延遲非必要的腳本:

<!-- 會封鎖解析器 (應避免) -->
<script src="/critical.js"></script>

<!-- 延遲載入 (首選) -->
<script defer src="/app.js"></script>

<!-- 非同步 (適用於獨立腳本) -->
<script async src="/analytics.js"></script>

<!-- 模組 (預設為延遲) -->
<script type="module" src="/app.mjs"></script>

程式碼分割模式:

// 基於路由的分割
const Dashboard = lazy(() => import('./Dashboard'));

// 基於元件的分割
const HeavyChart = lazy(() => import('./HeavyChart'));

// 基於功能的分割
if (user.isPremium) {
  const PremiumFeatures = await import('./PremiumFeatures');
}

Tree Shaking 最佳實踐:

// ❌ 導入整個函式庫
import _ from 'lodash';
_.debounce(fn, 300);

// ✅ 僅導入需要的部分
import debounce from 'lodash/debounce';
debounce(fn, 300);

圖片最佳化

格式選擇

格式使用案例瀏覽器支援
AVIF照片,最佳壓縮92%+
WebP照片,良好備援97%+
PNG帶透明度的圖形通用
SVG圖示、標誌、插圖通用

響應式圖片

<picture>
  <!-- 為現代瀏覽器使用 AVIF -->
  <source 
    type="image/avif"
    srcset="hero-400.avif 400w,
            hero-800.avif 800w,
            hero-1200.avif 1200w"
    sizes="(max-width: 600px) 100vw, 50vw">
  
  <!-- WebP 備援 -->
  <source 
    type="image/webp"
    srcset="hero-400.webp 400w,
            hero-800.webp 800w,
            hero-1200.webp 1200w"
    sizes="(max-width: 600px) 100vw, 50vw">
  
  <!-- JPEG 備援 -->
  <img 
    src="hero-800.jpg"
    srcset="hero-400.jpg 400w,
            hero-800.jpg 800w,
            hero-1200.jpg 1200w"
    sizes="(max-width: 600px) 100vw, 50vw"
    width="1200" 
    height="600"
    alt="Hero image"
    loading="lazy"
    decoding="async">
</picture>

LCP 圖片優先級

<!-- Above-fold LCP 圖片:急切載入,高優先級 -->
<img 
  src="hero.webp" 
  fetchpriority="high"
  loading="eager"
  decoding="sync"
  alt="Hero">

<!-- Below-fold 圖片:延遲載入 -->
<img 
  src="product.webp" 
  loading="lazy"
  decoding="async"
  alt="Product">

字型最佳化

載入策略

/* 系統字型堆疊作為備援 */
body {
  font-family: 'Custom Font', -apple-system, BlinkMacSystemFont, 
               'Segoe UI', Roboto, sans-serif;
}

/* 防止不可見文字 */
@font-face {
  font-family: 'Custom Font';
  src: url('/fonts/custom.woff2') format('woff2');
  font-display: swap; /* 或對非關鍵字型使用 optional */
  font-weight: 400;
  font-style: normal;
  unicode-range: U+0000-00FF; /* 子集化為拉丁字母 */
}

預載關鍵字型

<link rel="preload" href="/fonts/heading.woff2" as="font" type="font/woff2" crossorigin>

可變字型

/* 一個檔案取代多種字重 */
@font-face {
  font-family: 'Inter';
  src: url('/fonts/Inter-Variable.woff2') format('woff2-variations');
  font-weight: 100 900;
  font-display: swap;
}

快取策略

Cache-Control 標頭

# HTML (短時間或無快取)
Cache-Control: no-cache, must-revalidate

# 帶有雜湊的靜態資產 (不可變)
Cache-Control: public, max-age=31536000, immutable

# 不帶雜湊的靜態資產
Cache-Control: public, max-age=86400, stale-while-revalidate=604800

# API 回應
Cache-Control: private, max-age=0, must-revalidate

Service Worker 快取

// 靜態資產優先使用快取
self.addEventListener('fetch', (event) => {
  if (event.request.destination === 'image' ||
      event.request.destination === 'style' ||
      event.request.destination === 'script') {
    event.respondWith(
      caches.match(event.request).then((cached) => {
        return cached || fetch(event.request).then((response) => {
          const clone = response.clone();
          caches.open('static-v1').then((cache) => cache.put(event.request, clone));
          return response;
        });
      })
    );
  }
});

執行時期效能

避免佈局抖動 (Layout Thrashing)

// ❌ 強制多次重新計算佈局
const heights = [];
elements.forEach(el => {
  const height = el.offsetHeight; // 讀取
  el.style.height = height + 10 + 'px'; // 寫入
});

// ✅ 批次讀取,然後批次寫入
const heights = elements.map(el => el.offsetHeight); // 所有讀取
elements.forEach((el, i) => {
  el.style.height = heights[i] + 10 + 'px'; // 所有寫入
});

防抖昂貴的操作

function debounce(fn, delay) {
  let timeout;
  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => fn(...args), delay);
  };
}

// 防抖滾動/調整大小處理器
window.addEventListener('scroll', debounce(handleScroll, 100));

使用 requestAnimationFrame

// ❌ 可能導致卡頓
setInterval(animate, 16);

// ✅ 與顯示器重新整理同步
function animate() {
  // 動畫邏輯
  requestAnimationFrame(animate);
}
requestAnimationFrame(animate);

虛擬化長列表

// 對於超過 100 項的列表,僅渲染可見項目
// 使用 react-window、vue-virtual-scroller 或原生 CSS 等函式庫:
.virtual-list {
  content-visibility: auto;
  contain-intrinsic-size: 0 50px; /* 估計的項目高度 */
}

使用 View Transitions 實現流暢導航

View Transitions API 讓瀏覽器使用單一 GPU 合成的快照,在兩個 DOM 狀態之間進行交叉淡入淡出(或自訂動畫)——無需雙重渲染、無佈局抖動,且快照不計入 CLS。

同文件 (SPA 風格) — Baseline 2026:

// 包裝用於交換檢視的 DOM 變異
function navigate(newView) {
  if (!document.startViewTransition) return swapDOM(newView);
  document.startViewTransition(() => swapDOM(newView));
}

跨文件 (MPA 風格) — Chromium 穩定,其他瀏覽器漸進增強:

/* 在來源頁面和目標頁面上 */
@view-transition { navigation: auto; }

這是完整的整合 — 同源的導航現在會自動淡入淡出。要將特定元素納入共享元素轉換(例如,縮圖展開為英雄圖),為它們提供匹配的 view-transition-name:

.product-thumb[data-id="42"], .product-hero { view-transition-name: product-42; }

將此與 Speculation Rules (見上文) 結合,以實現即時且帶有動畫的導航。

第三方腳本

載入策略

// ❌ 阻塞主執行緒
<script src="https://analytics.example.com/script.js"></script>

// ✅ 非同步載入
<script async src="https://analytics.example.com/script.js"></script>

// ✅ 延遲到互動後
<script>
document.addEventListener('DOMContentLoaded', () => {
  const observer = new IntersectionObserver((entries) => {
    if (entries[0].isIntersecting) {
      const script = document.createElement('script');
      script.src = 'https://widget.example.com/embed.js';
      document.body.appendChild(script);
      observer.disconnect();
    }
  });
  observer.observe(document.querySelector('#widget-container'));
});
</script>

Facade 模式

<!-- 在互動前顯示靜態佔位符 -->
<div class="youtube-facade" 
     data-video-id="abc123" 
     onclick="loadYouTube(this)">
  <img src="/thumbnails/abc123.jpg" alt="Video title">
  <button aria-label="播放影片">▶</button>
</div>

測量

每當 URL 可執行時,請使用測量工作流程。它定義了 Chrome DevTools MCP 路由、CrUX 與備援來源、可重複的實驗室條件,以及精簡的證據格式。

指標種類解讀
LCP, INP, CLS 在 p75 時現場使用者結果的 Core Web Vitals;用於通過/失敗優先級排序
追蹤中的 LCP, CLS實驗室單次導航的可重複診斷數值
TBT實驗室主執行緒阻塞診斷,以及粗略的 INP 代理,非現場 INP
FCP, Speed Index實驗室載入診斷,非 Core Web Vitals

原始的 PerformanceObserver 程式碼片段對於當前瀏覽器會話很有用,但它們本身並非真實使用者數據。當使用者想要生產環境的遙測時,請閱讀第一方 RUM 參考資料,並優先使用 web-vitals 而非手動實作的指標。

參考資料

如需特定於 Core Web Vitals 的優化,請參閱 Core Web Vitals。

Individual skills in this repo

This repo contains 4 individual skills — each has its own dedicated page.

相關技能