將下列指令新增到 Service Worker:

importScripts(
  'https://storage.googleapis.com/workbox-cdn/releases/6.4.1/workbox-sw.js'

這樣您就在 Service Worker 中會有 workbox 命名空間 提供所有 Workbox 模組的存取權。

workbox.precaching.*
workbox.routing.*

您開始使用其他模組後,系統會產生一些神奇的發揮效果。

首次參照模組時,workbox-sw 會偵測出這點 並在提供模組前載入您可以在 工具中的「網路」分頁

你的瀏覽器會快取這些檔案,方便日後使用 離線使用。

使用本機 Workbox 檔案 (而非 CDN)

如果不想使用 CDN,只要輕鬆改用 Workbox 檔案即可 託管在您自己的網域中

最簡單的方法是透過 workbox-clicopyLibraries 指令取得檔案,然後 workbox-sw 可透過 modulePathPrefix 設定選項找到這些檔案。

如果將檔案放入 /third_party/workbox-vX.Y.Z/ 底下,則應使用如下所示:

importScripts('/third_party/workbox-vX.Y.Z/workbox-sw.js');
workbox.setConfig({
  modulePathPrefix: '/third_party/workbox-vX.Y.Z/',

避免非同步匯入

實際上,首次載入新模組時,需要呼叫 importScripts()敬上 並附上對應 JavaScript 檔案的路徑 (可能由 CDN 代管或透過本機網址代管)。 無論是哪一種情況,您都會套用一項重要限制:對 importScripts() 的隱含呼叫只能 是在 Service Worker 的 install 處理常式內進行「或」同步期間 Service Worker 指令碼的「初始執行」

為避免違反這項限制,建議參照多種 任何事件處理常式或非同步函式以外的 workbox.* 命名空間。

舉例來說,可以使用下列頂層 Service Worker 程式碼:

importScripts(
  'https://storage.googleapis.com/workbox-cdn/releases/6.4.1/workbox-sw.js'
// This will work!
workbox.routing.registerRoute(
  ({request}) => request.destination === 'image',
  new workbox.strategies.CacheFirst()

不過,如果您在workbox.strategies Service Worker:

importScripts(
  'https://storage.googleapis.com/workbox-cdn/releases/6.4.1/workbox-sw.js'
self.addEventListener('fetch', event => {
  if (event.request.url.endsWith('.png')) {
    // Oops! This causes workbox-strategies.js to be imported inside a fetch handler,
    // outside of the initial, synchronous service worker execution.
    const cacheFirst = new workbox.strategies.CacheFirst();
    event.respondWith(cacheFirst.handle({request: event.request}));

如果您需要撰寫的程式碼會違反此限制,您可以明確 使用importScripts() workbox.loadModule() 方法:

importScripts(
  'https://storage.googleapis.com/workbox-cdn/releases/6.4.1/workbox-sw.js'
// This will trigger the importScripts() for workbox.strategies and its dependencies:
workbox.loadModule('workbox-strategies');
self.addEventListener('fetch', event => {
  if (event.request.url.endsWith('.png')) {
    // Referencing workbox.strategies will now work as expected.
    const cacheFirst = new workbox.strategies.CacheFirst();
    event.respondWith(cacheFirst.handle({request: event.request}));

另外,您也可以在事件處理常式外建立相關命名空間的參照, 然後,之後再使用該參照用於:

importScripts(
  'https://storage.googleapis.com/workbox-cdn/releases/6.4.1/workbox-sw.js'
// This will trigger the importScripts() for workbox.strategies and its dependencies:
const {strategies} = workbox;
self.addEventListener('fetch', event => {
  if (event.request.url.endsWith('.png')) {
    // Using the previously-initialized strategies will work as expected.
    const cacheFirst = new strategies.CacheFirst();
    event.respondWith(cacheFirst.handle({request: event.request}));

強制使用偵錯版本或正式環境

Workbox 模組中的所有版本都含有兩個版本,分別是偵錯版本 包含記錄和其他類型檢查,以及實際工作環境版本 會移除記錄和類型檢查

根據預設,workbox-sw 會使用偵錯版本,針對 localhost 上的網站使用偵錯版本。 但對於任何其他來源而言,則會使用正式版本

如要強制執行偵錯版本或正式版版本,您可以設定 debug 設定

workbox.setConfig({
  debug: true,

使用匯入陳述式轉換程式碼,以使用 workbox-sw

使用 workbox-sw 載入 Workbox 時,可透過以下方式存取所有 Workbox 套件: 全域 workbox.* 命名空間

如有想轉換的 import 陳述式的程式碼範例 使用 workbox-sw 時,您只需要載入 workbox-sw,並將所有 import 陳述式替換為參照的本機變數 全域命名空間中的這些模組

可正常運作的原因是,發布至 npm 的所有 Workbox 服務工作站套件也一樣 取得於全域 workbox 命名空間 名稱的 camelCase 版本 (例如 如要取得從 workbox-precaching npm 套件匯出的所有模組,請前往 workbox.precaching.*。從 Vertex AI Pipelines 匯出的所有模組 您可以在以下位置找到 workbox-background-sync npm 套件: workbox.backgroundSync.*)。

舉例來說,以下程式碼使用 import 陳述式參照 Workbox 模組:

import {registerRoute} from 'workbox-routing';
import {CacheFirst} from 'workbox-strategies';
import {CacheableResponse} from 'workbox-cacheable-response';
registerRoute(
  ({request}) => request.destination === 'image',
  new CacheFirst({
    plugins: [new CacheableResponsePlugin({statuses: [0, 200]})],

以下為使用 workbox-sw 重寫的相同程式碼 (請注意,只有 匯入陳述式已變更 - 邏輯尚未改變):

importScripts(
  'https://storage.googleapis.com/workbox-cdn/releases/6.4.1/workbox-sw.js'
const {registerRoute} = workbox.routing;
const {CacheFirst} = workbox.strategies;
const {CacheableResponse} = workbox.cacheableResponse;
registerRoute(
  ({request}) => request.destination === 'image',
  new CacheFirst({
    plugins: [new CacheableResponsePlugin({statuses: [0, 200]})],
  

除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。

上次更新時間:2017-11-27 (世界標準時間)。

[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2017-11-27 (世界標準時間)。"],[],[]]