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

服务周期性工作内容

In an earlier article of mine, I talked about 4 essential things every PWA must have, which service worker happens to be part of. Service worker plays a very vital role when it's comes to Progressive Web Apps (PWA), as it is 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.

在我的较早的文章中,我谈到了每个PWA必须具备的4个基本要素 ,而服务人员恰好是其中的一部分。 在涉及渐进式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 service worker runs in the background. Before we can start using service worker, we must register it as a background process. This is the first phase of the phase of the lifecycle. Since service worker is not currently supported in all browsers yet. When registering a service worker, we must first check to make sure the browser supports service worker. Below is a code we can use to register a service worker:

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

// 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 support service worker, that is, if the navigator object has a serviceWorker property. Only when it's supported that we would register the service worker. The register() takes the path to the service worker script and returns a promise.

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

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

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 service worker script, the register() 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 application specific tasks. For example, we could cache our application static assets at this point:

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

// 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() 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() 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() ,这将延迟服务工作者的安装,直到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进入已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() to active a service worker can look like below:

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

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

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

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:

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

The Service Worker Lifecycle

结论 ( Conclusion )

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

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

I hope you find this article helpful and let's continue the conversation in the comments section below.

希望本文对您有所帮助,让我们在下面的评论部分中继续讨论。

翻译自: https://scotch.io/tutorials/demystifying-the-service-worker-lifecycle

服务周期性工作内容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值