博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
服务周期性工作内容_使服务工作者生命周期神秘化
阅读量:2506 次
发布时间:2019-05-11

本文共 8637 字,大约阅读时间需要 28 分钟。

服务周期性工作内容

介绍 (Introduction)

Service workers play a very vital role in Progressive Web Apps (PWA), as they are responsible for offline caching, push notifications, background sync etc. In this article, we’ll be demystifying the service worker lifecycle and what can be done at each stage of the lifecycle.

服务工作者在渐进式Web应用程序(PWA)中扮演着非常重要的角色,因为他们负责离线缓存,推送通知,后台同步等。在本文中,我们将揭开服务工作者生命周期的神秘面纱,并说明每个工作可以做什么生命周期的阶段。

For effective use of service worker, an understanding of the service lifecycle is essential. The service worker lifecycle consists of mainly 3 phases, which are:

为了有效使用服务人员,必须了解服务生命周期。 服务人员的生命周期主要包括三个阶段,分别是:

  • Registration

    注册
  • Installation

    安装
  • Activation

    激活

Let’s go over each of them.

让我们逐一检查它们。

注册 (Registration)

A service worker is basically a JavaScript file. One thing that differentiate a service worker file from a normal JavaScript file, is that a service worker runs in the background, off the browser’s main UI thread. Before we can start using service worker, we must register it as a background process. This is the first phase of the lifecycle. Since service workers are not yet supported in all browsers, we must first check to make sure the browser supports service workers. Below is a code we can use to register a service worker:

服务工作者基本上是一个JavaScript文件。 服务工作程序文件与普通JavaScript文件之间的区别是,服务工作程序在后台运行,而不是浏览器的主UI线程。 在开始使用Service Worker之前,我们必须将其注册为后台进程。 这是生命周期的第一阶段。 由于并非所有浏览器都支持服务人员,因此我们必须首先检查以确保浏览器支持服务人员。 以下是我们可以用来注册服务人员的代码:

app.js
app.js
if ('serviceWorker' in navigator) {    navigator.serviceWorker.register('/sw.js')    .then(function (registration) {        console.log('Service worker registered!');    })    .catch(function (err) {        console.log('Registration failed!');    })}

First, we check if the browser supports service workers, that is, if the navigator object has a serviceWorker property. Only when it’s supported would we register the service worker. The register() method takes the path to the service worker script and returns a promise.

首先,我们检查浏览器是否支持服务工作者,即, navigator对象是否具有serviceWorker属性。 只有在支持的情况下,我们才能注册服务工作者。 register()方法采用服务工作者脚本的路径并返回承诺。

At the point of registering a service worker, we can also define the scope of the service worker. The scope of a service worker determines the pages that the service worker can control. By default, the scope is defined by the location of the service worker script.

在注册服务人员时,我们还可以定义服务人员的范围。 服务人员的范围决定了服务人员可以控制的页面。 默认情况下,范围由服务工作程序脚本的位置定义。

app.js
app.js
if ('serviceWorker' in navigator) {    navigator.serviceWorker.register('/sw.js', {        scope: '/blog/'    })    .then(function (registration) {        console.log('Service worker registered!');    })    .catch(function (err) {        console.log('Registration failed!');    })}

In addition to accepting the path to the service worker script, the register() method can also accept an optional object, where we can define the scope of the service worker. Here, we define the scope of the service worker to /blog/, which will limit the service worker to only the blog directory.

除了接受服务工作者脚本的路径之外, register()方法还可以接受一个可选对象,在这里我们可以定义服务工作者的scope 。 在这里,我们将服务人员的范围定义为/blog/ ,这会将服务人员的范围限制为仅blog目录。

安装 (Installation)

The fact that a service worker has been successfully registered doesn’t mean it has been installed. That’s where the installation phase of the lifecycle comes into play. Upon successful registration of the service worker, the script is downloaded and then the browser will attempt to install the service worker. The service worker will only be installed in either of these cases:

服务工作者已经成功注册的事实并不意味着它已经安装。 这就是生命周期的安装阶段起作用的地方。 成功注册服务工作者后,将下载脚本,然后浏览器将尝试安装服务工作者。 仅在以下两种情况中的一种情况下,才会安装服务工作者:

  • The service worker hasn’t been registered before

    之前尚未注册服务工作者
  • The service worker script changes (even if it’s by one byte).

    服务工作者脚本会更改(即使只有一个字节)。

Once a service worker has been installed, an install event is fired. We can listen for this event and perform some application0-specific tasks. For example, we could cache our application’s static assets at this point:

一旦安装了Service Worker,就会触发install事件。 我们可以侦听此事件并执行一些特定于application0的任务。 例如,此时我们可以缓存应用程序的静态资产:

sw.js
sw.js
const assetsToCache = [    '/index.html',    '/about.html',    '/css/app.css',    '/js/app.js',]self.addEventListener('install', function (event) {    event.waitUntil(        caches.open('staticAssetsCache').then(function (cache) {              return cache.addAll(assetsToCache);        })      );});

Here, we are using the open() method of the Cache API, which accepts the name of the cache (staticAssetsCache in this case) to either open (if it already exists) or create and returns a promise. Once the promise is resolved, that is, inside the then(), we again make use of the addAll() of the Cache API, which accepts an array of URLs to cache. Since the open() method will return a promise, we need wrap it inside event.waitUntil(), which will delay the installation of the service worker untill the promise is resolved. If the promise is rejected, the install event fails and the service worker will be discarded.

在这里,我们使用Cache API的open()方法,该方法接受缓存的名称(在本例中为staticAssetsCache )以打开(如果已经存在)或创建并返回staticAssetsCache 。 兑现承诺后,即在then()内部,我们再次使用Cache API的addAll() ,该API接受要缓存的URL数组。 由于open()方法将返回承诺,因此我们需要将其包装在event.waitUntil() ,这将延迟服务工作者的安装,直到承诺被解决event.waitUntil() 。 如果承诺被拒绝,则install事件将失败,并且服务人员将被丢弃。

激活 (Activation)

If the installation was successful, the service worker enters an installed state (though not yet active), during which it waits to take control of the page from the current service worker. It then moves on to the next phase in the lifecycle, which is the activation phase. A service worker is not immediately activated upon installation. A service worker will only be active (that is, be activated) in any of these cases:

如果安装成功,则服务工作者进入已installed状态(尽管尚未激活),在此期间,它将等待从当前服务工作者处获得对页面的控制。 然后,它进入生命周期的下一个阶段,即激活阶段。 安装后,服务人员不会立即激活。 在以下任何一种情况下,服务工作者将仅处于活动状态(即被激活):

  • If there is no service worker currently active

    如果当前没有服务人员
  • If the self.skipWaiting() is called in the install event handler of the service worker script

    如果在service worker脚本的install事件处理程序中调用了self.skipWaiting()

  • If the user refreshes the page

    如果用户刷新页面

An example of using the skipWaiting() method to activate a service worker can look like below:

使用skipWaiting()方法激活服务工作者的示例如下所示:

sw.js
sw.js
self.addEventListener('install', function (event) {    self.skipWaiting();    event.waitUntil(           // static assets caching      );});

An activate event is fired upon a service worker being active. Like the install event, we could also listen for the activate event and perform some application specific tasks. For for example, clearing out the cache:

服务人员处于活动状态时将activate事件。 像install事件一样,我们也可以侦听activate事件并执行一些特定于应用程序的任务。 例如,清除缓存:

sw.js
sw.js
const cacheVersion = 'v1';self.addEventListener('activate', function (event) {     event.waitUntil(         caches.keys().then(function (cacheNames) {            cacheNames.map(function (cacheName) {                if (cacheName.indexOf(cacheVersion) < 0) {                     return caches.delete(cacheName);                   }                 });             });        })     ); });

The snippet above loops through all the named caches and deletes any existing if the cache does not belongs to the current service worker.

上面的代码段循环遍历所有已命名的缓存,如果缓存不属于当前服务工作程序,则删除所有现有缓存。

Once the service worker has been activated, it now has full control of the pages. With the service worker active, it can now handle events such as fetch, push and sync.

激活服务工作者后,便可以完全控制页面。 在服务工作者处于活动状态时,它现在可以处理诸如fetchpushsync事件。

sw.js
sw.js
self.addEventListener('fetch', function (event) {    event.respondWith(caches.match(event.request))    .then(function (response) {        return response || fetch(event.request);    });});

If the service worker after being active, does not receive any of the functional events mentioned above, it goes into an idle state. After being idle for some time, the service worker goes into a terminated state. This does not mean the service worker has been uninstalled or unregistered. In fact, the service worker will become idle again as soon as it begins to receive the fuctional events.

如果服务工作者处于活动状态后没有收到上述任何功能事件,它将进入idle状态。 空闲一段时间后,服务工作者进入terminated状态。 这并不意味着服务工作者已被卸载或注销。 实际上,服务工作者一旦开始接收功能性事件,便会再次变得空闲。

Below is a visual summary of the service worker lifecycle:

以下是服务人员生命周期的直观摘要:

结论 (Conclusion)

In this article, we looked at the service worker lifecycle, the events that are emitted at end phase of the lifecycle. Also, we looked some possible things we could with a service worker by hooking into some of these events.

在本文中,我们研究了服务工作者的生命周期,即在生命周期结束阶段发出的事件。 此外,我们还通过研究其中一些事件来寻找服务工作者可以做的一些事情。

翻译自:

服务周期性工作内容

转载地址:http://cohgb.baihongyu.com/

你可能感兴趣的文章
Hdu1754-线段树-单点更新
查看>>
在python中使用正则表达式(一)
查看>>
asp.net mvc 4.0的部署
查看>>
WordPress资源站点推荐
查看>>
Python性能鸡汤
查看>>
android Manifest.xml选项
查看>>
Cookie/Session机制具体解释
查看>>
ATMEGA16 IOport相关汇总
查看>>
有意思的cmd命令
查看>>
js正則表達式语法
查看>>
JVM-垃圾回收
查看>>
VS2013 添加已有文件夹
查看>>
python 计时程序运行时间
查看>>
【Shell脚本学习4】几种常见的Shell
查看>>
Git学习系列-Git基本概念
查看>>
c#多个程序集使用app.config 的解决办法
查看>>
模仿网站登录注册
查看>>
Linux+Apache+PHP+MySQL服务器环境配置(CentOS篇)
查看>>
Linux下获取本机IP地址的代码
查看>>
(C#)调用Webservice,提示远程服务器返回错误(500)内部服务器错误
查看>>