How Can I Claim A Client When Initializing A Serviceworker To Prevent Having To Reload The Page?
Solution 1:
Firstly, you are seem to be getting the error because of a typo in your code. See notes about it at the bottom.
Besides, skipWaiting()
and Clients.claim()
does both install and activate new SW with a single request. But quite naturally you will only get static assets like css after you reload.
So, even when equipped with skipWaiting()
and Clients.claim()
, you need two page reloads to see updated static
content like new html or styles;
Page load #1
- Request to
sw.js
is made, and since SW contents is changedinstall
event is fired on it. - Also
activate
event is fired, since you haveself.skipWaiting()
in yourinstall
handler. - Consequently, your
activate
handler run and there is yourself.clients.claim()
call. Which will order the SW to take over the control of all the clients which under control of it's predecessor. - At this point, assets in cache are updated and your pages are all controlled by new service worker. Any Ajax request in range of service worker will return newly cached responses, for example.
Page load #2
Your app loads, and your SW responds from cache by hijacking the requests as usual. But now caches are up-to-date, and user gets to use app completely with new assets.
The error you are getting
Uncaught (in promise) TypeError: Illegal invocation
error must be due to a missing a parenthesis in your activate
handler;
event.waitUntil(self.clients.claim()
.then(caches.keys)
.then(function(cache_name_list) {
return Promise.all(
cache_name_list.map(function() {...}
); <-- Here is our very lonely single parenthesis.
})
);
That error should go away if you fix it.
Post a Comment for "How Can I Claim A Client When Initializing A Serviceworker To Prevent Having To Reload The Page?"