Get Started(開始)
Create and Register a Service Worker File(創建和注冊 Service Worker)
- Before we can use Workbox, we need to create a service worker file and register it to our website.(在使用Workbox之前,我們需要創建一個服務工作者文件并將其注冊到我們的網站。)
<script>
if ('serviceWorker' in navigator) {// Use the window load event to keep the page load performant(使用窗口加載事件保持頁面加載性能)window.addEventListener('load', () => {navigator.serviceWorker.register('/service-worker.js');});
}
</script>
- Looking in the “Application” tab in Chrome DevTools you should see your service worker registered.(在chrome devtools中的“application”選項卡中,您應該看到服務工作者已注冊。)
- Click the “Update on reload” checkbox to make it easier to develop with your new service worker.(單擊 “Update on reload” 復選框,以便與新的 service worker 一起開發。)

Importing Workbox(導入工作框)
- To start using Workbox you just need to import the workbox-sw.js file in your service worker.(要開始使用Workbox,只需在服務工作者中導入Workbox-sw.js文件。)
- Importing workbox-sw.js will create a workbox object inside of your service worker, and that instance is responsible for importing other helper libraries, based on the features you use.(導入workbox-sw.js將在服務工作者內部創建一個workbox對象,該實例負責根據您使用的功能導入其他助手庫。)
- Due to restrictions in the service worker specification, these imports need to happen either inside of an install event handler, or synchronously in the top-level code for your service worker.(由于 service worker 規范中的限制,這些導入需要在安裝事件處理程序內部或在服務工作者的頂級代碼中同步進行。?)
importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js'); // 同步的if (workbox) {console.log(`Yay! Workbox is loaded ?`);
} else {console.log(`Boo! Workbox didn't load ?`);
}
Using Workbox
- The easiest way to do this is to register a route with Workbox that will match any .js files that are requested, which we can do with a regular expression:(在Workbox中注冊一個路由,這里我們使用正則表達式去匹配請求的任何.js文件)
- If we want our JavaScript files to come from the network whenever possible, but fallback to the cached version if the network fails, we can use the “network first” strategy to achieve this.(如果我們希望我們的javascript文件盡可能來自網絡,但是如果網絡失敗,我們可以回退到緩存版本,我們可以使用“network first”策略來實現這一點。)
workbox.routing.registerRoute(new RegExp('.*\.js'),new workbox.strategies.NetworkFirst()
);
- Add this code to your service worker and refresh the page. If your web page has JavaScript files in it, you should see some logs similar to this:(在控制臺會有相應策略的打印提醒)

- Workbox provides a few caching strategies that you can use.(Workbox提供了一些您可以使用的緩存策略。)
- your CSS could be served from the cache first and updated in the background(可以先從緩存中提供CSS,然后在后臺進行更新。)
workbox.routing.registerRoute(// Cache CSS files./\.css$/,// Use cache but update in the background.new workbox.strategies.StaleWhileRevalidate({// Use a custom cache name.(使用自定義緩存名稱。?)cacheName: 'css-cache',})
);
- your images could be cached and used until it’s a week old, after which it’ll need updating.(使圖像被緩存并使用一周,一周后才更新。)
workbox.routing.registerRoute(// Cache image files./\.(?:png|jpg|jpeg|svg|gif)$/,// Use the cache if it's available.(如果緩存可用,請使用它。)new workbox.strategies.CacheFirst({// Use a custom cache name.cacheName: 'image-cache',plugins: [new workbox.expiration.Plugin({// Cache only 20 images.(只有20個圖像)maxEntries: 20,// Cache for a maximum of a week.(最多一周的緩存。)maxAgeSeconds: 7 * 24 * 60 * 60,})],})
);
What Else Can Workbox Do?
- Routing and caching strategies are performed by the routing and strategies modules, but there are plenty of other modules, each offering specific behaviors that you can use in your service worker.(路由和緩存策略是由路由和策略模塊執行的,但是還有許多其他模塊,每個模塊都提供可以在服務工作者中使用的特定行為。)
Precache Files(預緩存文件)
- If you want your web app to work offline or there are assets you know can be cached for a long time, precaching is the best approach.(當需要離線使用網頁或有需要加載很久的資源時,使用預緩存)
- Workbox provides an easy way to precache files, ensuring that as your service worker changes, the precached files are maintained efficiently, only downloading updated files and cleaning up after the service worker is made redundant.(Workbox提供了一種簡單的預緩存文件的方法,確保隨著服務工作者的更改,預緩存文件得到有效的維護,只下載更新的文件,并在服務工作者被冗余后進行清理。)
- The above snippet will download the files /styles/index.0c9a31.css, /scripts/main.0d5770.js and /index.html during the service worker install event and create a route that serves these files directly from the cache.(上述代碼段將在ServiceWorker安裝事件期間下載文件/styles/index.0c9a31.css、/scripts/main.0d5770.js和/index.html,并創建直接從緩存為這些文件提供服務的路由。)
- This list of files is normally generated using a tool that manages the versioning of files.(此文件列表通常使用管理文件版本控制的工具生成。)
workbox.precaching.precacheAndRoute(['/styles/index.0c9a31.css','/scripts/main.0d5770.js',{ url: '/index.html', revision: '383676' },
]);
Generating a Precache Manifest(生成預緩存清單)
- Below is a list of tools that can generate this list of files.(下面是可以生成此文件列表的工具列表。)
- Workbox Command Line Interface (CLI):Ideal for developers who are unfamiliar with Node or have simple needs.(非常適合不熟悉節點或有簡單需求的開發人員。)
- workbox Build:Perfect for developers wanting to programmatically build the list in Node or are using Gulp for their build process.(非常適合希望以編程方式在節點中構建列表或在其構建過程中使用Gulp的開發人員。)
- Workbox Webpack Plugin:Ideal for developers using webpack to build their project.(非常適合使用Webpack構建項目的開發人員。)
CLI(Precache Files with Workbox CLI)
Gulp or Node(Precache Files with workbox-build)
Webpack(Precache Files with Webpack)
Route Requests(路由請求)
- There are three ways developers can match a request with workbox-routing.(開發人員可以通過三種方式將請求與Workbox路由相匹配。)
- A string.
- A regular expression.(正則表達式。)
- A callback function.(回調函數。)
Matching a Route with a String(將路由與字符串匹配)
- The only thing to be wary of is that this would only match for requests on your origin. (這只會與源站上的請求匹配。)
workbox.routing.registerRoute('/logo.png',handler // 這里應該是處理程序,這個例子先用handler占個位置,以下同
);
- Instead you’d need to define the entire URL to match.(匹配源之外的路徑,需要定義整個URL來匹配。)
workbox.routing.registerRoute('https://some-other-origin.com/logo.png',handler
);
Matching a Route with a Regular Expression(將路由與正則表達式匹配)
- The regular expression provided is tested against the full URL.(提供的正則表達式根據完整的URL進行測試)
workbox.routing.registerRoute(new RegExp('\\.js$'),jsHandler
);workbox.routing.registerRoute(new RegExp('\\.css$'),cssHandler
);workbox.routing.registerRoute(new RegExp('/blog/\\d{4}/\\d{2}/.+'),handler
);
- If we wanted a route that would match that general path pattern made against both same- and cross-origin requests, using a regular expression with a wildcard (.+)at the start is one approach:(如果我們想要一個路由與針對相同和跨源請求的常規路徑模式相匹配,那么在開始使用帶有通配符(.+)的正則表達式是一種方法:?不在頭部添加通配符,只能匹配同源的?)
workbox.routing.registerRoute(new RegExp('.+/blog/\\d{4}/\\d{2}/.+'),handler
);
Matching a Route with a Callback Function(將路由與回調函數匹配)
- The callback will receive an object with the requests URL and the FetchEvent received in the service worker.(回調將接收一個對象,該對象具有在 service worker 中接收到的請求URL和FetchEvent。)
- One thing to note is that if you return a value in the match callback, it’ll be passed into the handler callback as a params argument.(如果在matchFunction回調中返回一個值,它將作為params參數傳遞到處理程序回調handler中。)
const matchFunction = ({url, event}) => {// Return true if the route should match // 路由匹配則返回 truereturn false;
};workbox.routing.registerRoute(matchFunction,handler
);
——————————————————————
- There are two ways you can handle a request:(有兩種方法可以處理請求:)
- Use one of Workbox’s strategies provided by workbox.strategies.(使用Workbox.Strategies提供的Workbox策略)
- Provide a callback function that returns a Promise that resolves to a Response(提供一個回調函數,該函數返回解析為響應的承諾?)
Handling a Route with a Workbox Strategy(使用 Workbox 策略處理路由)
- Most routes can be handled with one of the built in caching strategies.(大多數路由都可以通過一種內置的緩存策略來處理。)
- Stale While Revalidate(緩存優先,隨后更新):This strategy will use a cached response for a request if it is available and update the cache in the background with a response form the network. (If it’s not cached it will wait for the network response and use that). (如果請求可用,則此策略將使用緩存響應,并使用來自網絡的響應在后臺更新緩存。(如果沒有緩存,它將等待網絡響應并使用該響應)。)
- Network First(網絡優先):This will try and get a request from the network first. If it receives a response, it’ll pass that to the browser and also save it to a cache. If the network request fails, the last cached response will be used.(這將嘗試首先從網絡獲取請求。如果它收到一個響應,它將把它傳遞給瀏覽器,并將其保存到緩存中。如果網絡請求失敗,將使用上次緩存的響應。)
- Cache First(緩存優先,不更新):This strategy will check the cache for a response first and use that if one is available. If the request isn’t in the cache, the network will be used and any valid response will be added to the cache before being passed to the browser.(此策略將首先檢查緩存。如果請求不在緩存中,則將使用網絡,并在傳遞到瀏覽器之前將任何有效響應添加到緩存中。)
- Network Only(強制網絡):Force the response to come from the network.(強制響應來自網絡。)
- Cache Only(強制緩存):Force the response to come from the cache.
workbox.routing.registerRoute(match,new workbox.strategies.StaleWhileRevalidate()
);workbox.routing.registerRoute(match,new workbox.strategies.NetworkFirst()
);workbox.routing.registerRoute(match,new workbox.strategies.CacheFirst()
);workbox.routing.registerRoute(match,new workbox.strategies.NetworkOnly()
);workbox.routing.registerRoute(match,new workbox.strategies.CacheOnly()
);
- With each strategy you can customize the behavior of the Route by defining a custom cache to use and / or adding plugins.(每個策略,您可以定義要使用的緩存名 和 添加插件來定制路由的行為。定義相同的緩存名會怎樣?有什么意義?一個緩存名可以保存一組緩存數據,不同的緩存名是為了保存同一個接口不同的返回數據嗎?)
- These options are often needed to make it safer when caching requests (i.e. limiting how long they are cached or making sure the data used on a device is limited).(緩存請求時,通常需要這些選項以使其更安全。例如:限制緩存的時間或保存空間)
new workbox.strategies.StaleWhileRevalidate({// Use a custom cache for this route.(為此路由使用自定義緩存。)cacheName: 'my-cache-name',// Add an array of custom plugins (like workbox.expiration.Plugin).(添加一組自定義插件,例如 workbox.expiration.Plugin)plugins: [...]
});
Handling a Route with a Custom Callback(使用自定義回調處理路由)
- you can provide an asyncfunction which returns a Response object.(傳入一個返回 Response 對象的Async Function來處理。)
- Fetch API 的 Response 接口代表一次請求的響應數據
- It'll be called with a parameter object containing url and event (the FetchEvent) properties.(它將接收 URL 和 fetchvent 事件對象)
const handler = async ({url, event}) => {return new Response(`Custom handler response.`);
};workbox.routing.registerRoute(match, handler);
- One thing to note is that if you return a value in the match callback, it’ll be passed into the handler callback as a params argument.(如果在match回調中返回一個值,它將作為params參數傳遞到處理程序回調中。)
const match = ({url, event}) => {return {name: 'Workbox',type: 'guide',};
};const handler = async ({url, event, params}) => {// Response will be "A guide to Workbox"return new Response(`A ${params.type} to ${params.name}`);
};workbox.routing.registerRoute(match, handler);
- By default, Workbox will only create two caches, one for precaching and one for runtime caching. Using workbox-core you can get the current cache names like so:(默認情況下,Workbox將只創建兩個緩存,一個用于預緩存,另一個用于運行時緩存。使用Workbox Core,您可以獲得當前緩存名稱,如下所示:)
const precacheCacheName = workbox.core.cacheNames.precache;
const runtimeCacheName = workbox.core.cacheNames.runtime;
- Both the precache and runtime cache names are made of three pieces of information:
<prefix>-<cacheId>-<suffix>
(預緩存和運行時緩存名稱都由三條信息組成:) - You can alter the cache names by altering all or some of these pieces of information:(可以通過更改以下信息來更改緩存名稱:)
- We recommend changing the prefix for each of your projects. This allows you to work on multiple projects using the same localhost port number without mixing up the caches.(我們建議更改每個項目的前綴。這允許您使用相同的本地主機端口號處理多個項目,而不會混淆緩存。)
workbox.core.setCacheNameDetails({prefix: 'my-app',suffix: 'v1',precache: 'custom-precache-name',runtime: 'custom-runtime-name'
});
Custom Cache Names in Strategies(策略中自定義緩存名稱)
- but it’s not uncommon to want additional caches for specific uses, such as a cache just for images.(需要額外的緩存用于特定用途并不少見,例如只用于圖像的緩存。)
- In these cases, the cache name will be used exactly as you specify; the prefix and suffix will not be used.(在這些情況下,緩存名稱將完全按照您指定的方式使用。不會出現前綴和后綴)
/\.(?:png|jpg|jpeg|svg|gif)$/,new workbox.strategies.CacheFirst({cacheName: 'my-image-cache',})
);
Custom Fetch Options in Strategies(策略中自定義提取選項)
- you might find the need to customize some aspects of the outgoing requests.you can pass in a configuration value named fetchOptions to a strategy's constructor, corresponding to the init options used in the underlying Fetch API. (您可能會發現需要自定義傳出請求的某些方面。您可以將名為fetchOptions的配置值傳遞給策略的構造函數,對應于底層fetch api中使用的init選項。)
workbox.routing.registerRoute(new RegExp('https://third-party\\.example\\.com/'),new workbox.strategies.NetworkFirst({fetchOptions: {credentials: 'include',},})
);