Reputation: 480
When I change some code in service worker,I expect to update previous service worker in the browsers.I have read that any changes in service-worker.js automatically refreshes it in the browser This is my service worker code:
var dataCacheName = 'demo-v5';
var filesToCache = [
'/',
'/Home/Index',
'/Home/AboutUs'
];
self.addEventListener('install', function (e) {
console.log('[Service Worker] Install');
e.waitUntil(
caches.open(dataCacheName).then(function (cache) {
console.log('[Service Worker] Caching app shell');
return cache.addAll(filesToCache);
})
);
});
self.addEventListener('activate', function(e) {
console.log('[ServiceWorker] Activated');
caches.keys()
e.waitUntil(
// Get all the cache keys (cacheName)
caches.keys().then(function(cacheNames) {
return Promise.all(cacheNames.map(function(thisCacheName) {
// If a cached item is saved under a previous cacheName
if (thisCacheName !== dataCacheName) {
// Delete that cached file
console.log('[ServiceWorker] Removing Cached Files from Cache - ', thisCacheName);
return caches.delete(thisCacheName);
}
else
{
console.log('Else- ', thisCacheName);
}
}));
})
); // end e.waitUntil
// return self.clients.claim();
});
self.addEventListener('fetch', function (e) {
console.log('[Service Worker] Fetch', e.request.url);
var dataUrl = 'https://query.yahooapis.com/v1/public/yql';
if (e.request.url.indexOf(dataUrl) > -1) {
e.respondWith(
caches.open(dataCacheName).then(function (cache) {
return fetch(e.request).then(function (response) {
cache.put(e.request.url, response.clone());
return response;
});
})
);
} else {
e.respondWith(
caches.match(e.request).then(function (response) {
return response || fetch(e.request);
})
);
}
});
Upvotes: 3
Views: 5803
Reputation: 480
Thanks for your reply.
The Actual problem was with filesToCache
.The root directory i.e "/"
var filesToCache = [
// '/',
'/Home/Index',
'/Home/AboutUs'
];
should be commented here. My service-worker class was also getting cached and every time it was picking it from the cache after refresh also.
Upvotes: 3
Reputation: 31
The changes in service worker will reflect in second refresh of your page. If It is not updating even on second refresh than look for service worker errors in Chrome Developer Console (I hope you already use it). It will be under
Applications -> Service Worker
in chrome Developer tools (Latest stable Chrome version).
Open Chrome Developer tools by Clicking Ctrl + Shift + I
or Right click -> Inspect Element
.
NOTE: If you want service worker to update on first refresh then change your install event to -
self.addEventListener('install', function (e) {
console.log('[Service Worker] Install');
e.waitUntil(
caches.open(dataCacheName).then(function (cache) {
console.log('[Service Worker] Caching app shell');
return cache.addAll(filesToCache);
}).then(function(e){
return self.skipWaiting();
})
);
});
Upvotes: 2