Service work+cache can be used to cache some resources of the website locally, or even realize offline access (if your website is purely static).

The specific science popularization of this technology will not be repeated in this article. You can refer to this article: With the help of Service Worker and cacheStorage caching and offline development And this article PWA Service Worker: from introduction to actual combat to pit climbing

The latest version of the handhome theme also uses this technology to achieve local caching. Maybe you will feel very fast when you first enter the blog for subsequent visits. This may be the reason.

Simple implementation

Before introducing the sw update cache scheme, let's briefly introduce the working principle of sw.

We register a sw.js through the register api. At this time, the code of the js file will run in an independent js environment. It does not need to access the dom, but it has higher permissions.

 window.addEventListener('load', function() { navigator.serviceWorker.register('/sw.js').then(function(registration) { // Registration was successful console.log('ServiceWorker registration successful with scope: ',  registration.scope); }, function(err) { // registration failed :( console.log('ServiceWorker registration failed: ', err); }); });

At this point, you will enter the life cycle of the sw. The following figure shows the life cycle of the service worker Google official documents See related introduction:

 Service Worker Lifecycle

We usually judge whether to delete the old cache (based on the cache key) in the activated state.

One of the powerful functions of sw is the fetch event , can capture all requests under the current domain. We can capture requests through this event, decide whether to directly return to the cache or make network requests, and even modify the request header and response body. The results obtained from network requests can be used to determine whether caching is required.

Update Cache

This article mainly discusses how to update the local cache in the user's browser when the cached content needs to be updated.

The life cycle of sw is: install ->waiting ->activate ->fetch

That is, start registration and wait for activation. After activation, listen to the request of the page.

Sw.js uses this function navigator.serviceWorker.register(url:string) To register a service worker.

When executing this function, the browser will reinstall the new version (install ->Waiting) if it finds that the file content of this url has been modified (compared with the previously registered sw)

The browser will replace the last sw when it is idle (for example, no request occurs on the page), instead of executing it immediately, which is why there is a waiting phase.

But we can use the skipWaiting Force skip waiting.

sw.min.js :

 self.addEventListener('install', function(event) { Event. waitUntil (self. skipWaiting())//This will trigger the activate event });

Although the document says self.skipWaiting This function can jump the queue and directly force retirement of the old version. However, after specific experiments, we found that if there are multiple tabs under a domain name, we still need to wait for a short time on edge and chrome, and we can quickly replace the old version on safari and firefox. (You can see the current website's sw process in the developer tool - application - service worker process)

Therefore, this method cannot be used to directly update the local cache.

Even if it is executed serviceWorker.register You can force the old version to be replaced. When you open a web page, you will still use the resources in the cache (you need to refresh again to use the latest resources).

as a result of serviceWorker.register This is a js that executes asynchronously. Even if it is placed at the front of the page, some resources will still be loaded in the register Before execution, if these resources are previously cached, the cache will be called directly instead of the latest resources.

So the better way is to, After the new sw is successfully installed, the user is prompted to refresh the browser to update the local cache

You can monitor whether the new sw version is installed through this function provided by the browser:

 navigator.serviceWorker.addEventListener('controllerchange', function (ev) { //A prompt bar appears, prompting you to click the refresh page to update the local cache });

In this article Handle Service Worker updates carefully Method 3 is a similar idea, but it gives a prompt that if the user does not click, the new version of sw will not be installed. If the user is lazy, and has been lazy, the old version of the cache will be used consistently.

My above practice is that the user will install a new version of sw even if he does not click the prompt bar. The old version of the cache has been loaded on the current page, but the next time the user enters the page (or manually re swipes the page), it will be the latest (although he does not click the prompt bar).

Last modification: December 31, 2021
Do you like my article?
Don't forget to praise or appreciate, let me know that you accompany me on the way of creation.