0

The page at https://googlechrome.github.io/samples/service-worker/basic/ has all the script you need for getting started with modern offline web pages. I spent many fruitless hours researching the subject before I stumbled on it. Suddenly, all the stuff I'd been reading started to make sense. Yet again HTML5 impresses me as a superb development system.

It has a small snippet of script that needs to be run in your main page and it has the complete script of a service worker that will fetch files from your server when you're online - or fetch them from cache when you're offline.

It took me less than an hour to get it working. N.B. You can test it using http on localhost. You'll need an https connection for any other server. The Google and Firefox debuggers do not show the source of the serviceworker.

It was clear from the start that the functionality demonstrated in the serviceworker example was very close to what I need for my app but I think I have discovered a bug.

The activation handler is supposed to take care of cleaning up old caches. Here is the script - verbatim from the page.

// Names of the two caches used in this version of the service worker.
// Change to v2, etc. when you update any of the local resources, which will
// in turn trigger the install event again.
const PRECACHE = 'precache-v1';
const RUNTIME = 'runtime';

// The activate handler takes care of cleaning up old caches.
self.addEventListener('activate', event => {
  const currentCaches = [PRECACHE, RUNTIME];
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return cacheNames.filter(cacheName => !currentCaches.includes(cacheName));
    }).then(cachesToDelete => {
      return Promise.all(cachesToDelete.map(cacheToDelete => {
        return caches.delete(cacheToDelete);
      }));
    }).then(() => self.clients.claim())
  );
});

Put simply, it's not deleting old caches. I think it's trying to delete caches before it has executed the filter to determine which ones are not needed.

I'm an experienced programmer but this snippet scares me. It's beautifully short for a production app but hard to read if you're debugging it. It would have been good if the author had written it in a more verbose manner so that more developers could understand what's going on.

How does it work?

halfer
  • 19,824
  • 17
  • 99
  • 186

1 Answers1

0

const PRECACHE = 'precache-v1'; const RUNTIME = 'runtime';

self.addEventListener("activate", function(event) {
    event.waitUntil(
        caches.keys().then(function(cacheNames) {
            return Promise.all(
                cacheNames.map(function(cacheName) {
                    if (PRECACHE !== cacheName && RUNTIME != cacheName) {
                        return caches.delete(cacheName);
                    }
                })
            );
        })
    );
});
    })
  );
});
Dave S
  • 849
  • 7
  • 7