`self.Clients.claim()`有什么用? [英] What is the use of `self.Clients.claim()`

查看:399
本文介绍了`self.Clients.claim()`有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要注册服务工作者,我可以致电

To register a service worker, I can call

navigator.serviceWorker.register('/worker.js')

每次页面加载时都会检查 worker.js的更新版本。如果找到更新,则在关闭所有页面的选项卡然后重新打开之前,不会使用新工作程序。我读到的解决方案是:

Every time the page loads it checks for an updated version of worker.js. If an update is found, the new worker won't be used until all the page's tabs are closed and then re-opened. The solution I read was:

self.addEventListener('install', function(event) {
  event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', function(event) {
  event.waitUntil(self.clients.claim());
});

我可以理解skipWaiting部分,但究竟是什么 clients.claim( )吗?我已经完成了一些简单的测试,即使没有它也似乎按预期工作。

I can understand the skipWaiting part, but what exactly does clients.claim() do? I've done some simple tests and it seems to work as expected even without it.

推荐答案

我正在摘录以下内容服务工作者生命周期指南

I'm excerpting the following from a guide to the service worker lifecycle:


clients.claim

你可以通过在服务工作者激活后调用
clients.claim()来控制不受控制的客户。

You can take control of uncontrolled clients by calling clients.claim() within your service worker once it's activated.

这是以上演示的变体,其中调用 clients.claim()
中激活事件。你应该第一次看到一只猫。我说
应该,因为这是时间敏感的。如果服务工作者激活
,并且 clients.claim()在图像尝试加载
之前生效,您将只看到一只猫。

Here's a variation of the demo above which calls clients.claim() in its activate event. You should see a cat the first time. I say "should", because this is timing sensitive. You'll only see a cat if the service worker activates and clients.claim() takes effect before the image tries to load.

如果您使用服务工作者加载页面的方式不同于通过网络加载的
clients.claim()可能会很麻烦,因为你的
服务工作者最终会控制一些没有
的客户端。

If you use your service worker to load pages differently than they'd load via the network, clients.claim() can be troublesome, as your service worker ends up controlling some clients that loaded without it.

注意:我看到很多人包括clients.claim()作为样板,
但我自己很少这样做。它只对最初的
负载非常重要,并且由于渐进式增强,无论如何,页面通常都是愉快地工作

Note: I see a lot of people including clients.claim() as boilerplate, but I rarely do so myself. It only really matters on the very first load, and due to progressive enhancement the page is usually working happily without service worker anyway.

这篇关于`self.Clients.claim()`有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆