跳轉至

建立 2026-11-23 更新 2026-11-23

快取策略

快取策略是 Service Worker 在 fetch 事件中決定「這個請求該從快取拿、從網路拿,還是兩者並用」的規則。沒有一種策略適用所有檔案:靜態資源要快、API 資料要新、使用者頭像可以稍舊。本頁先介紹 Cache API 的基本操作,再說明五種常見策略各自適合哪類資源。

Cache API 怎麼用?

Cache API(Cache Storage)是瀏覽器提供的「請求 → 回應」鍵值儲存區,Service Worker 與網頁都能使用。它和瀏覽器的 HTTP 快取是兩回事:HTTP 快取由瀏覽器依標頭自動管理,Cache Storage 則完全由你的程式決定存什麼、存多久、何時刪除。

const cache = await caches.open('static-v1');      // 開啟(或建立)一個快取

await cache.addAll(['/', '/app.css', '/app.js']);  // 下載並存入多個網址
await cache.put(request, response.clone());        // 存入自己取得的回應

const res = await caches.match(request);           // 在所有快取中尋找
await caches.delete('static-v0');                  // 刪除整個舊快取

回應只能讀一次

Response 的內容是串流,讀過就沒了。同一個回應既要回給頁面、又要存進快取時,必須先 response.clone()。

五種常見快取策略

快取優先(Cache First)

先找快取,有就直接回傳;沒有才上網,並把結果存起來。速度最快,但檔案更新後使用者不會自動拿到新版。

async function cacheFirst(request) {
  const cached = await caches.match(request);
  if (cached) return cached;
  const response = await fetch(request);
  const cache = await caches.open('static-v1');
  cache.put(request, response.clone());
  return response;
}

適合:檔名帶雜湊值的 JS/CSS(app.3f9a1c.js)、字型、圖示——內容變了檔名就會變,不怕拿到舊檔。

網路優先(Network First)

先上網,成功就更新快取並回傳;網路失敗(或逾時)才退回快取。資料最新,但網路慢時使用者要等。

async function networkFirst(request) {
  const cache = await caches.open('pages-v1');
  try {
    const response = await fetch(request);
    cache.put(request, response.clone());
    return response;
  } catch {
    return (await cache.match(request)) ?? caches.match('/offline.html');
  }
}

適合:HTML 頁面、文章內容、經常變動的 API 資料。

先回快取、背景更新(Stale-While-Revalidate)

有快取就立刻回傳,同時在背景上網抓新版更新快取,下次造訪就是新的。兼顧速度與新鮮度,代價是使用者這次看到的可能是上一版。

async function staleWhileRevalidate(event) {
  const cache = await caches.open('runtime-v1');
  const cached = await cache.match(event.request);
  const network = fetch(event.request).then((response) => {
    cache.put(event.request, response.clone());
    return response;
  });
  event.waitUntil(network.catch(() => {}));   // 讓背景更新可以做完
  return cached ?? network;
}

適合:使用者頭像、商品圖片、不需要即時正確的清單。

只用網路(Network Only)

完全不經過快取。

適合:付款、登入、送出表單等 POST 請求,以及即時性要求極高的資料。

只用快取(Cache Only)

只從快取回傳,找不到就失敗。

適合:在 install 階段已經預先快取、保證存在的 App 殼層(App Shell)檔案。

如何依資源類型套用不同策略?

在 fetch 事件中依網址或 request.destination 分流:

self.addEventListener('fetch', (event) => {
  const { request } = event;
  const url = new URL(request.url);

  if (request.method !== 'GET') return;                       // 非 GET 交給瀏覽器
  if (request.mode === 'navigate') {
    event.respondWith(networkFirst(request));                 // HTML 頁面
  } else if (['style', 'script', 'font'].includes(request.destination)) {
    event.respondWith(cacheFirst(request));                   // 靜態資源
  } else if (request.destination === 'image') {
    event.respondWith(staleWhileRevalidate(event));           // 圖片
  } else if (url.pathname.startsWith('/api/')) {
    event.respondWith(networkFirst(request));                 // API
  }
});

沒有呼叫 event.respondWith() 的請求,會照瀏覽器原本的方式處理。

什麼是 App Shell 模式?

App Shell(應用程式殼層)指的是 App 的介面骨架:頁首、導覽、版面 CSS 與主要 JS。App Shell 模式是在 install 時把殼層全部預先快取,之後每次開啟都瞬間顯示骨架,再用網路載入內容填進去。這是單頁應用(SPA)做 PWA 最常見的架構,效果就像原生 App 打開時先出現介面、內容再逐步載入。

快取要如何清理?

  • 用版本號命名快取:static-v2 上線時,在 activate 刪掉所有不是 static-v2 的快取。
  • 限制動態快取的數量:圖片這類無上限成長的快取,存入後檢查 cache.keys() 的數量,超過就刪掉最舊的幾筆。
  • 不要快取錯誤回應:存入前檢查 response.ok,避免把 404 或 500 存起來一直回給使用者。

手寫這些邏輯很容易出錯,正式專案建議交給 Workbox 處理。

相關資料