admin管理员组

文章数量:1389772

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?

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?

Share Improve this question edited Jun 22, 2017 at 16:38 Louis 152k28 gold badges286 silver badges329 bronze badges asked Feb 19, 2017 at 21:53 Avraam MavridisAvraam Mavridis 8,94022 gold badges87 silver badges135 bronze badges 8
  • Is the error actually "An unknown error occurred when fetching the script"? – guest271314 Commented Feb 19, 2017 at 22:01
  • Failed to load resource: net::ERR_INTERNET_DISCONNECTED – Avraam Mavridis Commented Feb 19, 2017 at 22:10
  • You call fetch() when offline at return fetch(event.request);? – guest271314 Commented Feb 19, 2017 at 22:13
  • @guest271314 How is that related? The error I think is related on fetching the actual service worker sw.js file. Question updated with screenshot – Avraam Mavridis Commented Feb 19, 2017 at 22:18
  • Does sw.js fetch itself? Or are you expecting two separate ServiceWorker instances? – guest271314 Commented Feb 19, 2017 at 22:20
 |  Show 3 more ments

1 Answer 1

Reset to default 5

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

本文标签: javascriptServiceWorker not working offlineStack Overflow