Why browser loads service worker when going offlin

2019-08-02 17:15发布

问题:

I register the service worker with this code:

    // If the browser supports serviceWorker, and we haven't registered any - we'll register our: sw.js ..
if ('serviceWorker' in navigator && !navigator.serviceWorker.controller) {
    navigator.serviceWorker.register('/sw.js').then(function(registrationObj) {
        console.log('Registration object: ', registrationObj);
    }).catch(function(error) {
        // serviceWorker registration failed ..
        console.log('Registration failed with ' + error);
    });
} else {
    console.log('Service worker already registered. Skip registration.')
};

I see my assets appear in the app cache. Then I go to the Application tab in Chrome, choose Service Workers, click offline and refresh the page. The page opens fine, but I get this in browser console:

http://www.screencast.com/t/1uodUTHM5ig

and this in the Service Worker debugger:

http://www.screencast.com/t/zmqHMi9RJ

回答1:

Probably because you do not have service worker in cache (And quite naturally. It is not supposed to be cached in the first place.) so it falls back to standard http fetch process, and it fails as app is offline.

That error does not hinder anything and does not effect how your app works. It is just telling you that it has failed to fetch the script. And it was not suppose to success when the app is offline anyway.

Your service worker script probably structured like this;

    event.respondWith(
        caches.match(event.request).then(function (response) {
            if (response) {
                return response;
            }
            // request for service worker .js file falls here as it is not in the cache
            // this fails of course since the app is offline
            return fetch(event.request).then(function (response) {
                return response;
            });
        })
    );