工作盒快取-快取

在執行階段快取資產時,沒有一體適用的規則來判定特定回應是否為「有效」且符合儲存並重複使用的資格。

workbox-cacheable-response 模組提供判定回應是否應快取的標準方法,包括:根據數字狀態碼、含有特定值的標頭,或兩者的組合。

根據狀態碼快取

您可以在策略的 plugins 參數中新增 CacheableResponsePlugin 執行個體,藉此設定 Workbox 策略,將一組狀態碼視為符合快取資格:

import {registerRoute} from 'workbox-routing';
import {CacheFirst} from 'workbox-strategies';
import {CacheableResponsePlugin} from 'workbox-cacheable-response';

registerRoute(
  ({url}) =>
    url.origin === 'https://third-party.example.com' &&
    url.pathname.startsWith('/images/'),
  new CacheFirst({
    cacheName: 'image-cache',
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
    ],
  })
);

這項設定會指示 Workbox 在處理對 https://third-party.example.com/images/ 的要求回應時,快取狀態碼為 0200 的所有要求。

根據標頭快取

您可以在建構外掛程式時設定 headers 物件,藉此設定 Workbox 策略來檢查特定標頭值是否存在做為加入快取的條件:

import {registerRoute} from 'workbox-routing';
import {StaleWhileRevalidate} from 'workbox-strategies';
import {CacheableResponsePlugin} from 'workbox-cacheable-response';

registerRoute(
  ({url}) => url.pathname.startsWith('/path/to/api/'),
  new StaleWhileRevalidate({
    cacheName: 'api-cache',
    plugins: [
      new CacheableResponsePlugin({
        headers: {
          'X-Is-Cacheable': 'true',
        },
      }),
    ],
  })
);

在處理含有 /path/to/api/ 的要求網址回應時,請查看名為 X-Is-Cacheable 的標頭 (伺服器會新增至回應)。如果有這個標頭存在,且將值設為「true」,則可以快取回應。

如果指定多個標頭,只要其中一個標頭就必須與關聯值相符。

根據標頭和狀態碼快取

您可以混用狀態和標頭設定。必須同時符合這兩個條件,回應才會被視為可供快取;換句話說,回應必須包含其中一個已設定的狀態碼,「並且」至少必須具有其中一個提供的標頭。

import {registerRoute} from 'workbox-routing';
import {StaleWhileRevalidate} from 'workbox-strategies';
import {CacheableResponsePlugin} from 'workbox-cacheable-response';

registerRoute(
  ({url}) => url.pathname.startsWith('/path/to/api/'),
  new StaleWhileRevalidate({
    cacheName: 'api-cache',
    plugins: [
      new CacheableResponsePlugin({
        statuses: [200, 404],
        headers: {
          'X-Is-Cacheable': 'true',
        },
      }),
    ],
  })
);

預設設定是什麼?

如果您使用 Workbox 的其中一個內建策略,但未明確設定 cacheableResponse.CacheableResponsePlugin,系統會使用下列預設條件,判斷是否應快取從網路收到的回應:

  • staleWithRevalidate 和 networkFirst:可視為可快取的回應狀態為 0 (例如不透明回應) 或 200 的回應。
  • cacheFirst:系統會將狀態為 200 的回應視為可快取的回應。

根據預設,回應標頭不會用來決定可快取性。

為何會有不同的預設值?

預設值會因狀態為 0 的回應 (即不透明回應) 而有所不同。由於不透明回應的「黑箱」性質,服務工作站無法得知回應是否有效,或是否反映跨來源伺服器傳回的錯誤回應。

針對包含部分更新快取回應的方法 (例如 stale 但 Revalidate 和 networkFirst) 的策略而言,如果下次更新快取,就有機會正確且成功的回應,從而緩解快取暫時性錯誤回應的風險。

針對需要快取收到的第一個回應並無限期重複使用該快取回應的策略,會快取及重複使用暫時性錯誤造成的後果更嚴重。為在預設情況下確保安全,CacheFirst 會拒絕儲存回應,除非其狀態碼為 200

進階用法

如要在 Workbox 策略外使用相同的快取邏輯,可以直接使用 CacheableResponse 類別。

import {CacheableResponse} from 'workbox-cacheable-response';

const cacheable = new CacheableResponse({
  statuses: [0, 200],
  headers: {
    'X-Is-Cacheable': 'true',
  },
});

const response = await fetch('/path/to/api');

if (cacheable.isResponseCacheable(response)) {
  const cache = await caches.open('api-cache');
  cache.put(response.url, response);
} else {
  // Do something when the response can't be cached.
}

類型

CacheableResponse

這個類別可讓您設定規則,決定 Response 需要哪些狀態碼和/或標頭,才會被視為可快取。

屬性

  • 建構函式

    void

    如要建立新的 CacheableResponse 執行個體,您必須至少提供其中一項 config 屬性。

    如果同時指定 statusesheaders,則 Response 必須同時符合兩個條件,才會視為可快取。

    constructor 函式如下所示:

    (config?: CacheableResponseOptions)=> {...}

  • isResponseCacheable

    void

    根據此物件的設定檢查回應,確認是否可快取。

    isResponseCacheable 函式如下所示:

    (response: Response)=> {...}

    • 則回應

      回應

      正在檢查快取性的回應。

    • returns

      boolean

      如果 Response 可快取,則為 true;如果不是,則為 false

CacheableResponseOptions

屬性

  • headers

    物件選用

  • 狀態

    number[] 選填

CacheableResponsePlugin

實作 cacheWillUpdate 生命週期回呼的類別。這樣就能更輕鬆地為透過 Workbox 內建策略提出的要求加入快取性檢查。

屬性

  • 建構函式

    void

    如要建立新的 CacheableResponsePlugin 執行個體,您必須提供至少一項 config 屬性。

    如果同時指定 statusesheaders,則 Response 必須同時符合兩個條件,才會視為可快取。

    constructor 函式如下所示:

    (config: CacheableResponseOptions)=> {...}