Nowadays, PWA is quite popular, and Service Worker is a key technology to realize PWA. Today, we will learn some basic knowledge and application scenarios about Service Worker.

What is a Server Worker

Let’s first take a look at the core definition of Server Worker in the official document:

Service Workers essentially act as a proxy server between the Web application and the browser, and can also act as a proxy between the browser and the network when the network is available.

This is a very accurate definition, but it may not be vivid for those who do not know Service Worker. Let’s have a more vivid understanding of this concept. Let’s take going to the bank to withdraw money as an example. The process is as follows:

From the above we can see, the bank’s money in the vault, the customer is not when you pick up the money directly to the vault, but need through the bank’s staff, and how much you need to inform the bank staff, and present the corresponding certificates, after the bank staff take out money from the Treasury to customers, and minus the corresponding amount from the account. The reason for this is easy to understand, because the vault is public and all customers’ money is kept in it, there is no guarantee that every customer will be able to take only their own money and update the vault records as they are.

When our application requests resources from the server, the process is similar:

Figure can be seen from the above, request resources in the process of the HTTP protocol in the process of draw money serves as a bank staff, client applications require resources on the server, but the application failed to go directly to the server access to resources, but through the HTTP protocol, the various Header information specified in the request, is the credentials when you pick up the money.

A Service Worker can be interpreted as creating a vault of its own on the client side. See the picture first:

When we need to withdraw money or obtain resources, we can first take from the local Treasury, the local Treasury does not have, and then through the original process to obtain. If we look back at the definition at the beginning of the article, we should be able to understand it.

Relationship between Service Worker and Cache

Normally, the client obtains a resource in the following three steps:

As for the optimization of requested resources, it generally focuses on the following three steps:

  1. Access to resources without making a request;
  2. Improve the speed of the server to find resources;
  3. Reduce the volume of returned content;

After reading the above part, we can find that when using the existing resources in the Service Worker, the client application does not enter the HTTP request process to obtain the resources. In other words, through the Service Worker, the client application can obtain the resources without making the request. This easily reminds us of caching. How does a Service Worker relate to strong and negotiated caches? Sorted out a graph, you can first see:

On the whole, the Cache types for an application to obtain a resource can be divided into four types as shown in the figure above, namely Service Worker, Memory Cache, Disk Cache and No Cache. The search sequence is from left to right. If a resource is found, the system returns. If no resource is found, the system continues to search until the resource is finally obtained. In the figure above, we can clearly see the position of Service Worker in cache types, as well as its relationship with strong cache and negotiated cache, which are often mentioned.

The Service Worker uses logic

After understanding the concept of Service Worker, let’s take a look at the basic usage logic of Servise Worker. The basic process of using it is to register a Woker first, then the browser will start a new thread in the background. After this thread is started, Some resources will be cached according to the code logic in the Service Worker. After the caching, the monitoring of page requests will be started. When the page request resources are monitored, the corresponding response can be made.

registered

The Service Worker object is saved in window.navigator. First, register method is called to register and a JS file is imported, which contains our Service Worker logic. The code is as follows:

navigator.serviceWorker.register('/sw.js')
.then(function(reg){
    console.log("success", reg);
}).catch(function(err) {
    console.log("error", err);
});
Copy the code

It should be noted that Service Worker is scoped. Its scope is the current path of the file. Service Worker files can only manage their own resources, for example, abcde.com/home/sw.js is scoped to abcde.com/home/.

The activation

The registered Service Worker can be seen in the debug tool. Here is a screenshot of the Chrome debug panel:

The contents in red boxes are some key information, such as the file name and path of the Service Worker, as well as the current state of the Service Worker. The state of the Service Worker can be divided into several types. STOPPED, STARTING, RUNNING, and STOPPING, such as in the RUNNING state in the screenshot above.

Only the Service Worker in the running state can take effect. In this case, the registered Service Worker needs to be loaded and activated. After registration, the Service Worker will automatically download and the install event will be triggered. We can listen for this event and download the resource as follows:

const CACHE_NAME = "demo-a";
this.addEventListener("install".function(event) {
    console.log("install service worker success");
    caches.open(CACHE_NAME);
    let cacheResources = ["https://abcde.com/demo.js"];
    event.waitUntil(
        caches.open(CACHE_NAME).then(cache= >{ cache.addAll(cacheResources); })); });Copy the code

The demo.js file is cached by the above code, and the Service Worker will activate it after downloading it:

this.addEventListener("active".function(event) {
    console.log("service worker active success");
});
Copy the code

At this point, we can see an active Service Worker through the developer tool. The overall process is roughly as follows:

It should be noted that the gray part in the figure is an independent special thread, not the browser rendering page js thread, so there is no need to worry about affecting page rendering when using the Service Worker.

update

After we register the Service Worker, we are still faced with the problem of updating it. When we iterate our business, we must update the Service Worker. After we understand the whole registration process, it is easy to understand the update.

When the application is loaded, the Service Worker file will be downloaded. There will be two files in the browser, one is the currently used Service Worker and the other is the newly downloaded Service Worker. When the newly downloaded file is downloaded, the browser will perform Diff operation on the two files. If the file is not updated, the newly downloaded Service Worker file will be discarded. If the file is changed, a new Service Worker will be loaded, but the newly loaded Service Worker will be in the Wating state and will not actually play a role. Only when there is no dependency on the running Service Worker in the entire browser, the running Service Worker will be discarded and the new Servier Worker will be activated.

Common Usage Scenarios

  1. Used for browser cache, improve loading speed;
  2. Implementing offline applications, PWA is so popular these days;
  3. To realize the active push of messages, adding a powerful interaction mode for Web applications;

compatibility

We have learned some basic knowledge of Service workers and some common usage scenarios. What is the compatibility of Service workers at present

At present, the mainstream modern browsers have good support, but so far the whole series of IE browsers do not support Service Worker, and there is one obvious feeling. In the process of information searching, I have read many blogs on the Internet, and different blogs also have the support degree of Service Worker when writing blogs at that time. It is clear that Service Worker support is growing rapidly, and as it does, more and more developers will use this technology in their projects.

It may not be long before Service workers really make PWA apps popular.