Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Service worker: Fetch event listener only works after page reload

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)
                            }
                    )
    );
});
like image 950
Lewis Quaife Avatar asked Jul 10 '17 09:07

Lewis Quaife


1 Answers

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

like image 189
Lewis Quaife Avatar answered Nov 10 '22 00:11

Lewis Quaife