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:
PFB the screen shot:
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.