工作盒食譜

許多常見的模式 (尤其是轉送快取的部分) 都很常見,因此能標準化為可重複使用的方案進行標準化。workbox-recipes 會以易於使用的套件提供這些功能,讓您能快速啟用功能強大的服務工作程式。

食譜

每個食譜都會結合多個 Workbox 模組,將這些模組組合成常用的模式。下方的食譜會顯示您在使用此模組時使用的食譜,以及該模組在幕後使用的等效模式,方便您自行編寫。

離線備用

如果上述三者有任何一個發生路由錯誤,離線備用配方可讓服務工作者提供網頁、圖片或字型,例如使用者離線且沒有命中快取時。在 Workbox Recipes 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],
      }),
    ],
  })
);

靜態資源快取

靜態資源快取最佳化方法可讓服務工作者以 stale-while-revalidate 快取策略回應靜態資源要求,特別是 CSS、JavaScript 和 Web Worker 要求,以便快速從快取中提供這些資產,並在背景中進行更新

這個方案支援透過 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],
      }),
    ],
  })
);

圖片快取

圖片快取方案可讓 Service Worker 以快取優先快取策略來回應圖片要求,一旦這些圖片出現在快取中,使用者就不需要再提出其他要求。

根據預設,這個方案最多會快取 60 張圖片,每 30 天最多可快取 60 張圖片,並且支援透過 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 字型快取

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,
      }),
    ],
  })
);

快速使用

結合所有方案後,服務工作人員就會使用網路優先快取策略回應網頁要求、使用過時的快取策略回應 CSS、JavaScript 和 Web Worker 要求、以快取優先策略回應圖片要求、適當快取 Google Fonts,以及提供離線備用網頁要求。方法如下:

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

pageCache();

googleFontsCache();

staticResourceCache();

imageCache();

offlineFallback();

類型

GoogleFontCacheOptions

屬性

  • cachePrefix

    string optional

  • maxAgeSeconds

    號碼 選填

  • maxEntries

    號碼 選填

ImageCacheOptions

屬性

  • cacheName

    string 選填

  • matchCallback
  • maxAgeSeconds

    號碼 選填

  • maxEntries

    號碼 選填

  • 外掛程式

    WorkboxPlugin[] 選用

  • warmCache

    string[] 選填

OfflineFallbackOptions

屬性

  • fontFallback

    string 選填

  • imageFallback

    string 選填

  • pageFallback

    string optional

PageCacheOptions

屬性

  • cacheName

    string 選填

  • matchCallback
  • networkTimeoutSeconds

    編號 選填

  • 外掛程式

    WorkboxPlugin[] 選用

  • warmCache

    string[] 選填

StaticResourceOptions

屬性

WarmStrategyCacheOptions

屬性

  • 策略
  • 網址

    string[]

方法

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,
)