简体   繁体   中英

ServiceWorker not working offline

I have a simple service worker

Install

self.addEventListener('install', function(event) {
  console.log('Service Worker Install...');
  // pre cache a load of stuff:
  event.waitUntil(
    caches.open(CURRENT_CACHES.prefetch)
      .then(function(cache) {
      return cache.addAll([
        '/android-chrome-192x192.png',
        '/android-chrome-512x512.png',
        '/apple-touch-icon.png',
        '/browserconfig.xml',
        '/favicon-16x16.png',
        '/favicon-32x32.png',
        '/favicon.ico',
        '/favicon.png',
        '/mstile-150x150.png',
        '/safari-pinned-tab.svg',
        '/app.css',
        '/bundle.js',
        '/sw.js'
      ])
      .then(function(){
        console.log('Caches added');
      })
      .catch(function(error){
        console.error('Error on installing');
        console.error(error);
      });
    })
  )
});

Activate

self.addEventListener('activate', function(event) {
  console.log('Service Worker Activate...');
  // Delete all caches that aren't named in CURRENT_CACHES.
  var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) {
    return CURRENT_CACHES[key];
  });

  event.waitUntil(
    caches.keys().then(function(cacheNames) {
      return Promise.all(
        cacheNames.map(function(cacheName) {
          if (expectedCacheNames.indexOf(cacheName) === -1) {
            // If this cache name isn't present in the array of "expected" cache names, then delete it.
            console.log('Deleting out of date cache:', cacheName);
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

Fetch

self.addEventListener('fetch', function(event) {
  console.log('Service Worker Fetch...');

  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        if(event.request.url.indexOf('facebook') > -1){
          return fetch(event.request);
        }
        if(response){
          console.log('Serve from cache', response);
          return response;
        }
      return fetch(event.request);
    })
    .catch(function(error){
      console.error('Error on fetching');
      console.error(error);
    })
  );
});

Although this works, and I see in my caches everything cached correctly:

在此处输入图片说明

When I turned the network off, and refresh, I am getting: An unknown error occurred when fetching the script. for the service worker.

在此处输入图片说明

Isnt supposed that the service worker will be already there? Why it has to be re-fetched?

In the installation step you have to cache / and also /index.html , or you can cache your requests after fetching them :

self.addEventListener('fetch', function(event) {
  console.log('Service Worker Fetch...');

  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        if(event.request.url.indexOf('facebook') > -1){
          return fetch(event.request);
        }
        if(response){
          console.log('Serve from cache', response);
          return response;
        }
        return fetch(event.request)
            .then(response =>
              caches.open(CURRENT_CACHES.prefetch)
                .then((cache) => {
                  // cache response after making a request
                  cache.put(event.request, response.clone());
                  // return original response
                  return response;
                })
            )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM