Why browser loads service worker when going offline and cause “An unknown error occurred when fetching the script.”?

偶尔善良 提交于 2019-12-13 17:21:16

问题


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;
            });
        })
    );


来源:https://stackoverflow.com/questions/41783061/why-browser-loads-service-worker-when-going-offline-and-cause-an-unknown-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!