This is the eighth article in a series dedicated to exploring JavaScript and the components it is built upon.
## Recommended (free): javascript (video)
As you probably already know, progressive web apps are only growing in popularity because they aim to make the web app user experience smoother, creating an experience that resembles a native app rather than a browser look and feel. . One of the main requirements for building a Progressive Web App is to make it very reliable in terms of network and loading - it should be usable under uncertain or non-existent network conditions. In this article, we’ll take a deep dive intoService Workers: how they work and what you should care about. Finally, we also list some of the unique advantages of Service Workers in which scenarios they are worth using.
Introduction
If you want to know more aboutService Workers, you can read the author's article about Web Workers.
Life cycle of Service Worker
The life cycle of Service Worker is completely separated from the web page. It includes the following stages:Download
This is when the browser downloads the.js file that contains the Service Worker.
Installation
To install a Service Worker for your web application, you must first register it, which can be done in JavaScript code. After registering the Service Worker, it prompts the browser to start the Service Worker installation step in the background. By registering a Service Worker, you can tell the browser the location of your Service Worker's JavaScript files. Take a look at the following code: #The above example code first checks whether the Service Worker API is supported in the current environment. If supported,/sw.js this Service Worker will be registered.
register() method can be called every time the page is loaded. The browser will determine whether the Service Worker has been registered, and will give correct processing according to the registration status.
register() An important detail of the method is the location of the Service Worker file. In this example, you can see that the Service Worker file is located at the root of the domain, which means that the Service Worker scope will be under this domain. In other words, this Service Worker will receive
fetch events for everything in this domain. If we register the Service Worker file in
/example/sw.js, then the Service Worker will only see the fetch events of pages starting with
/example/ (for example,
/example /page1/,
/example/page2/).
The bottom line is that if you install a Service Worker on your page, you run the risk of lazy loading and rendering - instead of making the page available to your users as quickly as possible.
Note that this situation only occurs when you visit the page for the first time. Subsequent page visits will not be affected by the Service Worker installation. Once the Service Worker is activated on the first visit to a page, it can handle load/cache events for subsequent visits to the web application. This all makes sense because it needs to be prepared to handle limited network connections.
Activate
After installing the Service Worker, the next step will be to activate it, which is a good opportunity to take care of old cache management.
After the activation step, the Service Worker will control all pages that fall within its scope, although the page for which the Service Worker was first registered will not be controlled until loaded again.
Once a Service Worker takes control, it will be in one of two states:
Service Worker life cycle is as follows:
Internal mechanism of Service Worker installation
After the page starts the registration process, take a look at what happens in the Service Worker script. It handles the install
event by adding an event listener to the Service Worker instance:
Here are the steps you need to take when handling an installation event:
For the most basic example, you need to define callbacks for installation events and decide which files to cache.
self.addEventListener('install', function(event) { // Perform install steps });
The following is a simple internal installation process of Service Worker:
From the above example code, we can get:
calledcaches.open()
and the cache name we want, then call cache.addAll()
and pass in the file array. This is a chain of promises ( caches.open() and cache.addAll() ). event.waitUntil()
The method accepts a promise and uses it to know how long the installation will take and whether it was successful.
If all files are successfully cached, the Service Worker will be installed. If one of the files fails to download, the installation step will fail. This means that you need to be careful when deciding on the list of files to cache during the installation step. Defining a long list of files will increase the chance that a file may not be cached, causing your service worker to not be installed.
Handling the install
event is completely optional, you can avoid it, in which case you don't need to perform any steps here.
Runtime Cache Request
After the Service Worker is installed, the user navigates to another page or refreshes the current page, the Service Worker will receive fetch
event. Here is an example that demonstrates how to return a cached resource or perform a new request and then cache the result:
The above process:
fetch
event, and in event.respondWith()
we pass a promise## from
caches.match() #. This method looks at the request and looks for any cached results from any caches created by the service worker.
Update Service Worker
When a user accesses your web application, the browser attempts to re-download the.js file containing the Service Worker code , which is done in the background.
waiting state.
Once the currently open page of your web application is closed, the old Service Worker will be killed by the browser, the new Service Worker takes over control, and its activation event will be fired
Why is it needed These? In order to avoid the problem of two versions of the web application running on different tabs at the same time - this is very common on the web and can produce very serious bugs (for example, using different methods when storing data locally in the browser) mode).
Delete data from cache
A common task that occurs in activation callbacks is cache management. The reason you want to do this in the activation callback is that if you were to clear all old caches during the installation step, any old Service Worker that is retaining all current pages will suddenly stop serving files from that cache.
Here is an example of how to delete some files that are not in the whitelist from the cache (in this example, there are two entities page-1 and page-2):
Reason for requiring HTTPS
When building a web application, use Service Workers over localhost, but once you deploy it to a production environment, you need to prepare Good HTTPS (This is the last reason to use HTTPS).
Using Service Worker, it is easy to hijack the connection and forge responses. Without using HTTPs, human web applications are vulnerable to hackers.
For greater security, you need to register the Service Worker on pages served over HTTPS to know that the Service Worker received by the browser has not been modified while being transmitted over the network.
Browser support
Browser support for Service Worker is getting better and better:
Service Workers features will become more and more complete and powerful
Some unique features provided by Service Workers include:
The above is the detailed content of JavaScript introduces the life cycle and usage scenarios of Service Worker. For more information, please follow other related articles on the PHP Chinese website!