Home  >  Article  >  Web Front-end  >  JavaScript introduces the life cycle and usage scenarios of Service Worker

JavaScript introduces the life cycle and usage scenarios of Service Worker

coldplay.xixi
coldplay.xixiforward
2020-12-22 17:40:372590browse

This is the eighth article in a series dedicated to exploring JavaScript and the components it is built upon.

JavaScript introduces the life cycle and usage scenarios of Service Worker

JavaScript introduces the life cycle and usage scenarios of Service Worker

## 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 into

Service 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 about

Service Workers, you can read the author's article about Web Workers.

What is Service Worker

Introduction to MDN:

Service Worker is a script running behind the browser, independent of the web page, and does not require A page or user interaction feature opens the door. Today, it includes push notifications and background sync functionality. In the future, Service Workers will support functionality including periodic sync or geofencing.

Basically, Service Worker is a type of Web Worker, more specifically, it is like Shared Worker:

    Service Worker runs in its own global context
  • It's not tied to a specific web page
  • It doesn't have access to the DOM
The reason this is an exciting API is that it allows you to support offline experiences, allowing Developers have full control over the experience.

Life cycle of Service Worker

The life cycle of Service Worker is completely separated from the web page. It includes the following stages:

    Download
  • Installation
  • Activation

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:

JavaScript introduces the life cycle and usage scenarios of Service Worker

#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.

The

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/).

Usually during the installation step, you need to cache some static resources. If all files are cached successfully, the service worker will be installed. If any files cannot be downloaded and cached, the installation step will fail and the service worker will not be activated (i.e. will not be installed). If this happens, don't worry and try again next time. However, this means that if it installs, you know you have these static resources in the cache.

If registration needs to occur after the loading event, this answers your question "whether registration needs to occur after the loading event". This is not necessary, but definitely recommended.

Why? Let’s consider the first time a user visits your web application. There is no Service Worker yet, and the browser has no way of knowing in advance whether it will eventually be installed. If a Service Worker is installed, the browser will need to spend extra CPU and memory for this extra thread, otherwise the browser will use these extra CPU and memory to render the web page.

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:

  • Handle fetch and message events that occur when a network request or message is made from a web page
  • Service Worker will be terminated to save memory

Service Worker life cycle is as follows:

JavaScript introduces the life cycle and usage scenarios of Service Worker

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:

  • Turn on a cache
  • Cache our files
  • Confirm that all required resources are cached

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:

JavaScript introduces the life cycle and usage scenarios 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:

JavaScript introduces the life cycle and usage scenarios of Service Worker

The above process:

  • In Here we define the 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.
  • If it is in the cache, the response content is restored.
  • Otherwise, fetch will be executed.
  • Check whether the status code is 200 and check whether the response type is basic, indicating that the response comes from our original request. In this case, requests for third-party resources are not cached.
  • The response is cached
If it passes the check, clone the response. This is because the response is a Stream, so it can only be consumed once. Now that you want to return the response used by the browser and pass it to the cache for use, you need to clone it so that you can send one to the browser and one to the cache.

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.

If there is a difference of one byte or more between the downloaded Service Worker file and the current Service Worker file, the browser will assume that the Service Worker file has been changed, and the browser will start a new Service Worker.

The new Service Worker will be started and the installation event will be removed. However, at this point, the old Service Worker is still controlling your web app's pages, which means the new Service Worker will enter the

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):

JavaScript introduces the life cycle and usage scenarios of Service Worker

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:

JavaScript introduces the life cycle and usage scenarios of Service Worker

Service Workers features will become more and more complete and powerful

Some unique features provided by Service Workers include:

  • Push Notification — Allow users to choose timely updates from web applications.
  • Background Sync — Allows operations to be delayed until the user has a stable connection. In this way, you can ensure that whatever the user wants to send can actually be sent.
  • Periodic synchronization (open later) — Provides an API to manage the regular background synchronization function.
  • Geofencing (Open to follow) — You can define parameters, also known as geofences, around areas of interest. When a device passes through the geofence, the web application receives a notification that allows for a better experience based on the user's geolocation.

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!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete

Related articles

See more