问题描述
要注册 Service Worker,我可以调用
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.
推荐答案
我从 服务工作者生命周期指南:
clients.claim
您可以通过调用来控制不受控制的客户端clients.claim()
一旦它被激活就在你的 Service Worker 中.
You can take control of uncontrolled clients by calling
clients.claim()
within your service worker once it's activated.
这里是演示的变体,它调用了 clients.claim()
在它的激活事件.你应该第一次看到一只猫.我说应该",因为这是时间敏感的.你只会看到一只猫,如果service worker 激活并且 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.
如果您使用 Service Worker 加载页面的方式与他们不同通过网络加载,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()` 有什么用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!