工作盒食譜

有許多常見的模式,特別是與轉送快取相關的模式,因此可以標準化為可重複使用的方案。workbox-recipes 會以易於使用的套件提供這些工作,讓您透過功能性高的 Service Worker 快速開始運作。

套件

每個方案都會結合多個 Workbox 模組,將這些模組組合成常用的模式。下列方案會顯示您使用這個模組時使用的方案,以及該模組在背景中使用的對等模式,您應自行編寫時使用。

離線備用廣告

離線備用方案可讓服務工作處理程序提供網頁、圖片或字型,當這三者的任一轉送發生錯誤,例如使用者離線且沒有快取命中時。在 Workbox 方案 6.1.0 版中,我們已移除透過預先快取快取這些項目的相關規定;為了達到回溯相容性,系統會先在預快取中尋找項目,再嘗試自己的快取。

根據預設,這個方案假設備用頁面為 offline.html,且沒有備用圖片或字型。如需所有設定選項的清單,請參閱離線備用廣告選項

只有在特定要求有相符的路徑時,系統才會套用離線備用廣告。如果您使用離線備用方案,則必須自行建立路徑。最簡單的方法是使用 setDefaultHandler() 方法建立路徑,並將 NetworkOnly 策略套用至所有要求,如下所示。其他方案 (例如頁面快取靜態資源快取映像檔快取) 則會為各自的快取設定路徑。同時使用離線備用和其中一種方案時,不一定要使用 setDefaultHandler()

食譜

import {offlineFallback} from 'workbox-recipes';
import {setDefaultHandler} from 'workbox-routing';
import {NetworkOnly} from 'workbox-strategies';

setDefaultHandler(new NetworkOnly());

offlineFallback();

模式

import {setCatchHandler, setDefaultHandler} from 'workbox-routing';
import {NetworkOnly} from 'workbox-strategies';

const pageFallback = 'offline.html';
const imageFallback = false;
const fontFallback = false;

setDefaultHandler(new NetworkOnly());

self.addEventListener('install', event => {
  const files = [pageFallback];
  if (imageFallback) {
    files.push(imageFallback);
  }
  if (fontFallback) {
    files.push(fontFallback);
  }

  event.waitUntil(
    self.caches
      .open('workbox-offline-fallbacks')
      .then(cache => cache.addAll(files))
  );
});

const handler = async options => {
  const dest = options.request.destination;
  const cache = await self.caches.open('workbox-offline-fallbacks');

  if (dest === 'document') {
    return (await cache.match(pageFallback)) || Response.error();
  }

  if (dest === 'image' && imageFallback !== false) {
    return (await cache.match(imageFallback)) || Response.error();
  }

  if (dest === 'font' && fontFallback !== false) {
    return (await cache.match(fontFallback)) || Response.error();
  }

  return Response.error();
};

setCatchHandler(handler);

暖策略快取

暖策略快取方案可讓您在服務工作站的 install 階段將所提供的網址載入快取,並使用提供的策略選項快取這些網址。如果您知道要快取的特定網址、想為路徑的快取暖機,或要在安裝期間快取網址的類似位置,就可以改用這個替代預先快取

如需所有設定選項的清單,請參閱暖策略快取選項

食譜

import {warmStrategyCache} from 'workbox-recipes';
import {CacheFirst} from 'workbox-strategies';

// This can be any strategy, CacheFirst used as an example.
const strategy = new CacheFirst();
const urls = ['/offline.html'];

warmStrategyCache({urls, strategy});

模式

import {CacheFirst} from 'workbox-strategies';
// This can be any strategy, CacheFirst used as an example.
const strategy = new CacheFirst();
const urls = ['/offline.html'];

self.addEventListener('install', event => {
  // handleAll returns two promises, the second resolves after all items have been added to cache.
  const done = urls.map(
    path =>
      strategy.handleAll({
        event,
        request: new Request(path),
      })[1]
  );

  event.waitUntil(Promise.all(done));
});

網頁快取

網頁快取方案可讓您的服務工作處理程序使用「網路優先」快取策略回應 HTML 網頁的要求,最好是經過最佳化調整的快取策略,讓快取回退能快速送達,使最大內容繪製分數不到 4.0 秒。

根據預設,這項方案假設網路逾時應為 3 秒,且支援透過 warmCache 選項進行快取暖機。如需所有設定選項的清單,請參閱網頁快取選項

食譜

import {pageCache} from 'workbox-recipes';

pageCache();

模式

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

const cacheName = 'pages';
const matchCallback = ({request}) => request.mode === 'navigate';
const networkTimeoutSeconds = 3;

registerRoute(
  matchCallback,
  new NetworkFirst({
    networkTimeoutSeconds,
    cacheName,
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
    ],
  })
);

靜態資源快取

靜態資源快取方案可讓服務工作人員回應靜態資源 (特別是 CSS、JavaScript 和 Web Worker 的要求) 的要求,並採用 stale-while-revalidate 快取策略,以便從快取中快速提供這些資產,並在背景進行更新。

這個方案支援透過 warmCache 選項進行快取暖身。如需所有設定選項的清單,請參閱靜態資源快取選項

食譜

import {staticResourceCache} from 'workbox-recipes';

staticResourceCache();

模式

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

const cacheName = 'static-resources';
const matchCallback = ({request}) =>
  // CSS
  request.destination === 'style' ||
  // JavaScript
  request.destination === 'script' ||
  // Web Workers
  request.destination === 'worker';

registerRoute(
  matchCallback,
  new StaleWhileRevalidate({
    cacheName,
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
    ],
  })
);

圖片快取

圖片快取方案可讓您的服務工作處理程序採用「快取優先」快取策略來回應圖片的要求,這樣一旦快取資料可供快取,使用者就無需再另外提出圖片要求。

根據預設,這個方案最多會快取 60 張圖片,每個圖片可連續 30 天儲存,並且支援透過 warmCache 選項進行快取暖身。如需所有設定選項的清單,請參閱圖片快取選項

食譜

import {imageCache} from 'workbox-recipes';

imageCache();

模式

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

const cacheName = 'images';
const matchCallback = ({request}) => request.destination === 'image';
const maxAgeSeconds = 30 * 24 * 60 * 60;
const maxEntries = 60;

registerRoute(
  matchCallback,
  new CacheFirst({
    cacheName,
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
      new ExpirationPlugin({
        maxEntries,
        maxAgeSeconds,
      }),
    ],
  })
);

Google Fonts 快取

Google Fonts 方案會快取 Google Fonts 要求的兩個部分:

  • 具有 @font-face 定義的樣式表,會連結至字型檔案。
  • 經過修訂的靜態字型檔案。

由於樣式表可能會經常變更,因此系統會使用「過時/重新驗證」快取策略。另一方面,字型檔案本身不會改變,且可使用「優先快取」策略。

根據預設,這個方案會在一年內快取最多 30 個字型檔案。如需所有設定選項的清單,請參閱 Google Fonts 快取選項

食譜

import {googleFontsCache} from 'workbox-recipes';

googleFontsCache();

模式

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

const sheetCacheName = 'google-fonts-stylesheets';
const fontCacheName = 'google-fonts-webfonts';
const maxAgeSeconds = 60 * 60 * 24 * 365;
const maxEntries = 30;

registerRoute(
  ({url}) => url.origin === 'https://fonts.googleapis.com',
  new StaleWhileRevalidate({
    cacheName: sheetCacheName,
  })
);

// Cache the underlying font files with a cache-first strategy for 1 year.
registerRoute(
  ({url}) => url.origin === 'https://fonts.gstatic.com',
  new CacheFirst({
    cacheName: fontCacheName,
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
      new ExpirationPlugin({
        maxAgeSeconds,
        maxEntries,
      }),
    ],
  })
);

快速用法

將所有方案結合後,服務工作站就會使用「網路優先」的快取策略來回應網頁要求、以「過時-while-revalidate」策略回應 CSS、JavaScript 和 Web Worker 要求、以先快取策略回應圖片要求、正確快取 Google Fonts,並為網頁要求提供離線備用服務。下列應用程式都能執行這些操作:

import {
  pageCache,
  imageCache,
  staticResourceCache,
  googleFontsCache,
  offlineFallback,
} from 'workbox-recipes';

pageCache();

googleFontsCache();

staticResourceCache();

imageCache();

offlineFallback();

類型

GoogleFontCacheOptions

屬性

  • cachePrefix

    字串 選用

  • maxAgeSeconds

    數字 選填

  • maxEntries

    數字 選填

ImageCacheOptions

屬性

  • cacheName

    字串 選用

  • matchCallback
  • maxAgeSeconds

    數字 選填

  • maxEntries

    數字 選填

  • 外掛程式

    WorkboxPlugin[] 選用

  • warmCache

    string[] 選填

OfflineFallbackOptions

屬性

  • fontFallback

    字串 選用

  • imageFallback

    字串 選用

  • pageFallback

    字串 選用

PageCacheOptions

屬性

  • cacheName

    字串 選用

  • matchCallback
  • networkTimeoutSeconds

    數字 選填

  • 外掛程式

    WorkboxPlugin[] 選用

  • warmCache

    string[] 選填

StaticResourceOptions

屬性

WarmStrategyCacheOptions

屬性

方法

googleFontsCache()

workbox-recipes.googleFontsCache(
  options?: GoogleFontCacheOptions,
)

[Google 字型]https://developers.google.com/web/tools/workbox/guides/common-recipes#google_fonts 快取方案的實作

參數

imageCache()

workbox-recipes.imageCache(
  options?: ImageCacheOptions,
)

[圖片快取方案]https://developers.google.com/web/tools/workbox/guides/common-recipes#caching_images 的實作

參數

offlineFallback()

workbox-recipes.offlineFallback(
  options?: OfflineFallbackOptions,
)

實作 [全面備用方案]https://developers.google.com/web/tools/workbox/guides/advanced-recipes#comprehensive_fallbacks。請務必在預先快取插入資料中加入備用項

參數

pageCache()

workbox-recipes.pageCache(
  options?: PageCacheOptions,
)

實作有網路逾時的頁面快取方案

參數

staticResourceCache()

workbox-recipes.staticResourceCache(
  options?: StaticResourceOptions,
)

[CSS 和 JavaScript 檔案方案]https://developers.google.com/web/tools/workbox/guides/common-recipes#cache_css_and_javascript_files 的實作方式

參數

warmStrategyCache()

workbox-recipes.warmStrategyCache(
  options: WarmStrategyCacheOptions,
)