Retrieve updated files and remove older cache in service worker

时间:2018-12-19 11:16:27

标签: javascript service-worker progressive-web-apps

I am trying to create a simple offline access using service worker.

HTML:

<html>
    <body>
        Hello World
    </body>
    <script src="sample.js"></script>
</html>

sample.js:

if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('sample-service.js');
};

sample-service.js:

var sampleCache = "sample1";
var cacheFiles = ['sample.html', 'sample.js'];

self.addEventListener('install', function (e) {
    e.waitUntil(caches.open(sampleCache).then(function (cache) {
        return cache.addAll(cacheFiles);
    }));
});

self.addEventListener('activate', function (event) {
    event.waitUntil(caches.keys().then(function (cacheNames) {
        return Promise.all(cacheNames.filter(function (cacheName) {
            if(cacheName!=sampleCache)
            return true;
        }).map(function (cacheName) {
            return caches.delete(cacheName);
        }));
    }));
});

self.addEventListener('fetch', function(event) {
    event.respondWith(
        caches.match(event.request).then(function(response) {
          return response || fetch(event.request);
        })
      );
   });

What I find is that the offline part works fine. I am able to access the html file even when the server is not running. However, if I update the html and change the version number of my cache in sample-service.js, I observe two things:

  • The updated HTML is not shown
  • The older cache is not deleted.

PFB the screen shot:

enter image description here

Where am I going wrong? I even closed the tab and opened it again. I even restarted the browser. But the updated html content is not shown.

0 个答案:

没有答案