Created
November 15, 2016 09:54
-
-
Save amitmerchant1990/4d5bb62b795b10cb593e8b585ae8a1a5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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