服务周期性工作内容_使服务工作者生命周期神秘化

news/2024/7/6 1:11:18

服务周期性工作内容

介绍 (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.

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

翻译自: https://www.digitalocean.com/community/tutorials/demystifying-the-service-worker-lifecycle

服务周期性工作内容


http://www.niftyadmin.cn/n/3649583.html

相关文章

Adobe Dreamweaver CC 2019 安装教程

一、DW简介 Adobe Dreamweaver&#xff0c;简称“DW”&#xff0c;中文名称 “梦想编织者”&#xff0c;最初为美国MACROMEDIA公司开发 &#xff0c;2005年被Adobe公司收购。DW是集网页制作和管理网站于一身的所见即所得网页代码编辑器。利用对 HTML、CSS、JavaScript等内容的…

Json的知识点全解析,解析json数据的好工具大全

一、Json知识点 待续。。。。。。 二、Json解析工具 1、fastjson网址&#xff1a;http://fastjson.codeplex.com/ 教程博客&#xff1a;fastjson教程&#xff08;http://blog.sina.com.cn/s/blog_7ffb8dd501013qas.html&#xff09;2、网站&#xff1a;bejson网址&#xff1a;h…

CentOS系统:自动化运维工具Ansible的安装与配置

一、Ansible工具简介 ansible是新出现的自动化运维工具&#xff0c;基于Python开发&#xff0c;集合了众多运维工具&#xff08;puppet、cfengine、chef、func、fabric&#xff09;的优点&#xff0c;实现了批量系统配置、批量程序部署、批量运行命令等功能。 二、Ansible的安…

flutter 状态管理_管理Flutter中的状态

flutter 状态管理Most non-trivial apps will have some sort of state change going on and over time managing that complexity becomes increasingly difficult. Flutter apps are no different, but luckily for us, the Provider package is a perfect solution for most…

我的“普鲁斯特问卷”

普鲁斯特因著作《追忆逝水年华》而闻名&#xff0c;当他十三岁及二十岁时&#xff0c;分别回答过一份涉及被提问者的生活、思想、价值观及人生经验的问卷&#xff0c;而这份问卷亦因为他特别的答案而受到世人的关注&#xff0c;后人还将这份问卷命名为“Proust Questionnaire&a…

华为认证HCIA-Kunpeng Application Developer单选习题总结

最近参加了华为HCIA-Kunpeng Application Developer的认证考试。所以分享一下在培训和备考过程中做的一些习题。 ▣ 考试总共90分钟&#xff0c;有60个题。分别有单选、多选和判断。总分1000分&#xff0c;600分过。 单选练习题 1.TaiShan服务器支持哪个中标麒麟版本&#xf…

Activity 详解(一)

activity类处于android.app包中&#xff0c;继承体系如下&#xff1a; 1.java.lang.Object 2.android.content.Context 3.android.app.ApplicationContext 4.android.app.Activity activity是单独的&#xff0c;用于处理用户操作。几乎所有的activity都要和用户打交道&#xff…

[SMSWAP]实例讲解制作OTA短信来自动配置手机WAP书签[附源码]

[SMS&WAP]实例讲解制作OTA短信来自动配置手机WAP书签编写者日期关键词郑昀ultrapower2005-9-5Sms wap ota 书签 空中下载 手机上网设置 WDP WSP WBXML源代码&#xff1a;http://www.cnblogs.com/Files/zhengyun_ustc/otasms.rar空中下载(OTA)的概念OTA&#xff0c;即Over T…