I have added a service worker to my page with the code below. It works well once the page has been reloaded and the worker already installed. But does not seem to catch any fetch events before the page is reloaded after I have seen the 'SW INSTALL' log.
app.js
navigator.serviceWorker.register('/worker.js').then((registration) =>
{
console.log('ServiceWorker registration successful with scope: ',
registration.scope);
}, (err) =>
{
console.log('ServiceWorker registration failed: ', err);
});
worker.js
self.addEventListener('install', function (event)
{
console.log("SW INSTALL");
});
self.addEventListener('fetch', function (event)
{
console.log("FETCHING", event);
event.respondWith(
caches.match(event.request)
.then(function (response, err)
{
// Cache hit - return response
if (response)
{
console.log("FOUND", response, err);
return response;
}
console.log("MISSED", event.request.mode);
return fetch(event.request)
}
)
);
});
Solution: Adding the following to worker.js;
self.addEventListener('activate', function (event)
{
event.waitUntil(self.clients.claim());
});
Service workers don’t immediately “claim” the sessions that load them, meaning that until your user refreshes the page your service worker will be inactive.
The reason for this is consistency, given that you might otherwise end up with half of your webpage’s assets cached and half uncached if a service worker were to come alive partway through your webpage’s initialization. If you don’t need this safeguard, you can call clients.claim and force your service worker to begin receiving events
Read more @ service-workers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With