What is the use of `self.Clients.claim ()`

To register a service worker, I can call

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

Each time a page loads it, an updated version of worker.js . If an update is found, the new worker will not be used until all tabs on the pages are closed and then reopened. The solution I read was:

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

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

+7
javascript frontend offline offline-caching service-worker
source share
2 answers

I am extracting the following from the manual of the desktop life cycle :

clients.claim

You can manage uncontrolled clients by calling clients.claim() in your worker after it is activated.

The following is a description of the demo above which clients.claim() calls in to clients.claim() its event. You should see the cat for the first time. I say β€œmust” because it is time sensitive. You will only see a cat if the activist activist of the service and clients.claim() takes effect before the image tries to load.

If you use your service worker to load pages differently than downloading via the network, clients.claim() can be difficult, as your service personnel will end up controlling some clients that load without it.

Note I see a lot of people, including clients.claim () as a template, but I rarely do it myself. This is really important in the first place, and due to progressive improvement, the page usually works happily without a service worker.

+6
source share

The service worker takes controls from the next page-reload after registering it. Using self.skipWaiting() and self.clients.claim() , you can ask the client to take control of the work service at the very first load .

eg

Let's say I cache the hello.txt files, and again if I make a call for hello.txt , it will make a server call, even if I have a resource in the cache. This is a scenario where I am not using self.clients.claim() . However, when you call the server for hello.txt to reload the next page, it will serve the resource from the cache.

To solve this problem, I must use a combination of self.skipWaiting() and self.clients.claim() so that the service worker starts serving the content immediately after it is activated.

PS:

next page-reload means renaming the page.

first load means the moment the page was first visited.

0
source share

All Articles