The Service worker is a script that runs in the background and is mainly used for network interaction between the browser and the server to implement some new functions. Workbox, on the other hand, is a library that Google has developed based on this feature, bringing some common functions out of the box. These two days after a study with them to add caching function for the blog, so write a record.

First, register the Serivce worker in the script of the page.

//scripts.js
if ('serviceWorker' in navigator) {
    jQuery(document).load(function () {
        navigator.serviceWorker.register('/sw.js')
    })
}
Copy the code

Since the service worker is scoped, it needs to be placed in the root directory of the website. Here I use the Nginx alias to resolve https://seewang.me/sw.js back to WordPress theme folder for easy management.

# nginx configuration file location = / sw. Js {alias/path/to/wordpress/wp - the content/themes/twentyfifteenone/js/sw. Js. }Copy the code

In sw.js, this is the content of the service worker script. You can first reference the Wordbox from the CDN, or download it and load it locally.

/ / sw. Js importScripts (' https://storage.googleapis.com/workbox-cdn/releases/3.4.1/workbox-sw.js')Copy the code

Then there is the cache logic

//sw.js
workbox.routing.registerRoute(
    /\/(en|zh)\/.+/,
    workbox.strategies.staleWhileRevalidate({
        cacheName: 'page-cache',
        plugins: [new workbox.expiration.Plugin({
            maxEntries: 200
        })]
    })
)
Copy the code

Workbox. Routing. RegisterRoute function in the first parameter to the regular expression matching resources, here I match all the pages in addition to the home page. The second parameter is the cache policy. The staleWhileRevalidate strategy here is to use the cache when the resource needs to be requested, but also asynchronously request the resource and update the cache so that the user can see the latest page the next time they visit. This not only improves speed, but also keeps resources up to date. There are other strategies to suit different scenarios

Test it out after deployment

Before use: