PS: This is my first article. Please point out any mistakes or unclear structures. I will try my best to improve them.

What is a workbox, what does a workbox do, and why do you use it? Before introducing Workbox, let’s take a look at service workers to help us understand workbox better.

A. The service worker

Service worker is a script that runs independently of web pages in the background of the browser. It can cache web requests, push and synchronize information to web pages. What’s more exciting is that it can realize the ability to see our web pages even when offline, greatly improving our user experience.

Service workers have been supported by a growing number of browsers, including Apple and Tencent X5 kernels. Apple already supports safari11. The support is as follows:

Why use Workbox

Workbox is a set of Web App static resources and local storage of request results by GoogleChrome team. The solution contains some Js libraries and build tools, and is presented for the first time in Chrome Submit 2017. Behind the Workbox are technologies and standards such as Service Worker and Cache API. Prior to Workebox, the GoogleChrome team released sw-precache and sw-toolbox libraries earlier, but from the GoogleChrome engineers’ point of view, workbox is a more perfect solution to handle offline capabilities easily and uniformly. Therefore, I stopped the maintenance of SW-precache and SW-Toolbox. So what problem does Workbox solve?

In the service worker, if we want to intercept and proxy all requests, we need to manually maintain a cache list. But now front-end development, most use Webpack, gulp, grant to build front-end code, resulting in our file name may often occur. At this time, especially for medium and large multi-page applications, the content of the cache list may be very large, manual maintenance is very troublesome, maintenance costs become very high.

Workbox was born to solve this problem.

Some features of WorkBox:

  • No matter how your site is built, you can achieve the effect of offline caching.
  • Manage the cache list automatically, including updating, synchronizing, deleting old cache, etc.
  • The configuration is simple but flexible and can be fully customized (support Service worker-related features such as Web Push, Background sync, etc.).
  • Multiple cache policies for various application scenarios.

3. Use of Workbox

Let’s look at the workbox example.

  1. In the onLoad of the entry page, register a service worker and import the cache list file (build.sw.js) when registering.

index.html

<script>
// Register A service worker
if ('serviceWorker' in navigator) {
  window.addEventListener('load'.function() {
    navigator.serviceWorker.register(`./build.sw.js`)
      .then(function(registration) {
        // Registration was successful
        console.log('[success] register ')},function(err) {
        // registration failed :(
        console.log('[fail]: ', err);
      });
  });
 <script>
}
Copy the code
  1. Configure the cache list and cache policy on the build.sw.js page
// The Workbox framework importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.3.0/workbox-sw.js'); / / immediately after registering successfully cached resource list workbox. Precaching. PrecacheAndRoute ([{"url": "css/index.css"."revision": "835ba5c3"
  },
  {
    "url": "images/xxx.png"."revision": "b1537bfs"
  },
  {
    "url": "index.html"."revision": "b331f695"
  },
  {
    "url": "js/index.js"."revision": "4d562866"}]); / / cache policy workbox. Routing. RegisterRoute (new RegExp (' '.*\.html'), workbox.strategies.networkFirst() ); workbox.routing.registerRoute( new RegExp('. * \. (? :js|css)'), workbox.strategies.cacheFirst() ); workbox.routing.registerRoute( new RegExp('https://your\.cdn\.com/'), workbox.strategies.staleWhileRevalidate() ); workbox.routing.registerRoute( new RegExp('https://your\.img\.cdn\.com/'), workbox.strategies.cacheFirst({ cacheName: 'example:img'}));Copy the code

The results are as follows:

Take a look at the build.sw.js file, which contains the cache list and cache policy. There are three ways to create workbox: workbox-webpack-plugin, workbox-cli, and workbox-build. Instead of discussing the implementation, let’s take a look at pre-cached lists and cache policies.

Pre-cached list

Precache precaching is what you’d expect if you were caching static resources that don’t update very often and only need to update when the hash value of the resource is changed.

Workbox provides a very convenient API to help us solve the problem of precache. We can configure it using workbox. Precaching in the following format:

workbox.precaching.precacheAndRoute([
  {
    "url": "URL of the file to be precached"."revision": "Cached hash value"},])Copy the code

Routing request cache

Routing request cache refers to through the files matching routing to adopt the mode of unused cache, this can be achieved by workbox. Routing. RegisterRoute for configuration. There are three routes matching modes:

  1. Matches are made using strings
/ / can be directly under the current project of absolute path workbox. Routing. RegisterRoute ('path/to/logo.png'Handler // Handler is the callback function that does the caching strategy, usually referring to what will be dropped later'Cache policy function'); / / can also be a complete with full URL path, the host URL here must be HTTPS workbox. Routing. RegisterRoute ('https://example.com/a/b/c.jpg',
    handler
);
Copy the code
  1. Matches are made by means of re
workbox.routing.registerRoute(
    new RegExp('.*\.(js|css|jpg|png|gif)'), // here is any re that can match the request route address handler);Copy the code

3. Use the callback function to match

Const customFun = ({url, event}) => {// Return if the request route matchestrueOr it can return a parameter object to be received by the handlerreturn false;
};

workbox.routing.registerRoute(
    customFun,
    handler
);
Copy the code

Caching strategies

The cache policy refers to how to cache the matched routes. Workbox provides two ways to configure caching policies

  • Caching strategies provided through the Workbox. Strategies API.
  • Provide a custom callback method that returns a Promise with a return result.

Workbox provides the following cache policies by default:

  • Stale While Revalidate
  • Network First
  • Cache First
  • Network Only
  • Cache Only

Stale While Revalidate

This strategy means that if the requested route has the corresponding Cache result, it will directly return the Cache result, and the network request will be made in the background to get the request result and update the Cache. If there is no Cache, it will directly send the network request and return the result. The usage is as follows:

Workbox. Routing. RegisterRoute (match, routing workbox. / / matching strategies. StaleWhileRevalidate ());Copy the code

Network First

If the network request is received, the result is returned to the client and written to the Cache. If the network request fails, The result of the cached Cache is returned to the client as follows:

Workbox. Routing. RegisterRoute (match, / / that match the routing workFirst workbox.strategies.net ());Copy the code

Cache First

If there is no result in the Cache, the network request will be made, the network request will be fetched, the result will be updated to the Cache, and the result will be returned to the client.

Workbox. Routing. RegisterRoute (match, routing workbox. / / matching strategies. CacheFirst ());Copy the code

Network Only

The more direct policy directly forces the normal network request and returns the result to the client. This policy is more suitable for the request with high real-time requirements.

Workbox. Routing. RegisterRoute (match, / / that match the routing workOnly workbox.strategies.net ());Copy the code

Cache Only

This strategy is also more direct, directly use the Cache results, and return the results to the client, this strategy is more suitable for static resource requests that do not change once online.

Workbox. Routing. RegisterRoute (match, routing workbox. / / matching strategies. CacheOnly ());Copy the code

The effect of using WorkerBox

In our project, we take the time of DomContentLoaded as a reference point to compare the situation of service workers with and without service workers.

The test conditions

Take the home page as an example. In different network environments, 10 network requests are initiated and the average is taken as the final result. The test results are as follows:

Several conclusions can be drawn from the above data:

  • In a weak environment, service worker has more and more obvious advantages.
  • Even in a wifi environment, the browser loads faster than when the service worker is not in use due to caching.
  • In the case of no network environment, the effect of offline cache can also be achieved, greatly improving the user experience of the page.

Five. A few points

Here are a few of the issues you may encounter while working with WorkBox:

1. Position of the service worker registration file

When registering a service worker on the page, try to register it in the root directory of the project, so as to give full play to the role of the service worker

/ / build. Sw. Js best under the root directory of the project, to maximize the cache effect. The navigator serviceWorker. Register (`. / build. Sw. Js `) / / if this configuration, Only directory path to achieve the following file cache and other directories, including root can't cache the navigator. ServiceWorker. Register (`. / path/build. Sw. Js `)Copy the code

2. Use the workbox command line to generate precautions for the pre-cached list

Assume your project is in the /app directory. Make sure there is an app/sw.js in your project root directory that contains the following content:

/ / sw in the project. Usually js source files are reserved by such an empty array to pre cache content list workbox. Precaching. PrecacheAndRoute ([]);Copy the code

This ensures that the generated pre-cached content list content is injected into the Service Worker file.

3. Set the cache policy

After a period of use and thinking, a more reasonable cache strategy is given:

  • HTML. If you want to make the page accessible offline, use NetworkFirst. If offline access is not required, use NetworkOnly.

  • CSS and JS, the situation is complicated, because the CSS and JS of general sites are in the CDN, SW has no way to determine whether the resources requested from the CDN are correct (HTTP 200), if the cache failed results, the problem will be big. It is suggested to use the stale-while-revalidate strategy to ensure the page speed, even if it fails, the user will update it once.

  • If the CSS, JS and site are in the same domain, and the file name has the Hash version number, you can use Cache First directly.

  • It is recommended to use Cache First and set a certain invalidation event. The request will not change once.

If you have a more friendly strategy in the process of using, please contribute your strategy, we learn together and make progress together.

Also, remember that Cache only and Cache first should never be used for any resource that is not in the same domain.

4. Running environment of service worker

Note that the Service Worker script can only run in HTTPS protocol, except that it can run in HTTP protocol when the domain name is localhost.

5. POST requests cannot be cached when the Service Worker is used to cache requests

Google’s standardization of the Web is still followed. SW regards POST requests as submitting resources to the server, and there is no need for caching


Reference Documents:

Developers.google.com/web/tools/w…

Zoumiaojiang.com/article/ama…