Skip to content

Instantly share code, notes, and snippets.

@boopathi
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save boopathi/57b7e8b6d657d55bdc7d to your computer and use it in GitHub Desktop.

Select an option

Save boopathi/57b7e8b6d657d55bdc7d to your computer and use it in GitHub Desktop.
sw.js
self.CACHE_NAME = ["cats-v", 14];
var cache_name = self.CACHE_NAME[0] + self.CACHE_NAME[1];
self.addEventListener('fetch', function(event) {
var cacheRequest = event.request.clone();
event.respondWith(caches.match(cacheRequest).then(function(response) {
if(response) return response;
var fetchRequest = event.request.clone();
return fetch(fetchRequest).then(function(response) {
var responseToCache = response.clone();
caches.open(cache_name).then(function(cache) {
var cacheSaveRequest = event.request.clone();
cache.put(cacheSaveRequest, responseToCache);
});
return response;
});
}));
});
// Now we need to clean up resources in the previous versions
// of Service Worker scripts
self.addEventListener('activate', function(event) {
var cachesToDelete = [];
for(var i=0;i<self.CACHE_NAME[1];i++) {
cachesToDelete.push(self.CACHE_NAME[0] + i);
}
console.log(cachesToDelete);
// Destroy the cache
event.waitUntil(caches.keys().then(function(cacheNames) {
return Promise.all(cacheNames.map(function(cacheName) {
if(cachesToDelete.indexOf(cacheName) !== -1) {
console.log("destroy:", cacheName);
return caches.delete(cacheName);
}
return Promise.resolve();
}));
}));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment