Skip to content

Instantly share code, notes, and snippets.

@amitmerchant1990
Created November 15, 2016 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amitmerchant1990/4d5bb62b795b10cb593e8b585ae8a1a5 to your computer and use it in GitHub Desktop.
Save amitmerchant1990/4d5bb62b795b10cb593e8b585ae8a1a5 to your computer and use it in GitHub Desktop.
importScripts('js/cache-polyfill.js');
var CACHE_VERSION = 'app-v1';
self.addEventListener('install', function (event) {
event.waitUntil(
caches.open(CACHE_VERSION)
.then(function (cache) {
console.log('Opened cache');
return cache.addAll(CACHE_FILES);
})
);
});
self.addEventListener('fetch', function (event) {
event.respondWith(
caches.match(event.request).then(function(res){
if(res){
return res;
}
requestBackend(event);
})
)
});
function requestBackend(event){
var url = event.request.clone();
return fetch(url).then(function(res){
//if not a valid response send the error
if(!res || res.status !== 200 || res.type !== 'basic'){
return res;
}
var response = res.clone();
caches.open(CACHE_VERSION).then(function(cache){
cache.put(event.request, response);
});
return res;
})
}
self.addEventListener('activate', function (event) {
event.waitUntil(
caches.keys().then(function(keys){
return Promise.all(keys.map(function(key, i){
if(key !== CACHE_VERSION){
return caches.delete(keys[i]);
}
}))
})
)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment