Skip to content

Instantly share code, notes, and snippets.

@hcastillaq
Created February 24, 2019 20:47
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 hcastillaq/1cb6b210277bf6174163cffb0ab938af to your computer and use it in GitHub Desktop.
Save hcastillaq/1cb6b210277bf6174163cffb0ab938af to your computer and use it in GitHub Desktop.
var CACHE_NAME = "hcq-cache";
var urlToCache = [
'/',
'/index.html',
'/css/fonts/MesloLGM-Regular.ttf'
];
self.addEventListener('install', function(event)
{
event.waitUntil(
caches.open(CACHE_NAME)
.then( function(cache){
return cache.addAll(urlToCache);
})
);
});
self.addEventListener('activate', function(event){
event.waitUntil(
caches.keys().then( cachesNames => {
return Promise.all(
cachesNames.map(cache => {
if(cache !== CACHE_NAME){
return caches.delete(cache);
}
})
)
})
);
});
self.addEventListener('fetch', function(event){
event.respondWith( fromCache(event.request) );
event.waitUntil( update(event.request) );
});
const fromCache = (request) => {
return caches.match(request.clone()).then( response => {
if( response ){ return response; }
if(request.mode != "navigate"){ return fetch(request.clone()); }
return fetch( request.clone() ).then( function(response) {
if(!response || response.status !== 200 || response.type !== 'basic') {
return caches.match('/').then( resp => resp);
}
caches.open(CACHE_NAME)
.then(function(cache) {
cache.put(request.clone(), response.clone());
});
return response;
});
});
}
const update = (request) => {
if( request.clone().mode == "navigate")
{
return caches.open(CACHE_NAME).then(function (cache) {
return fetch( request.clone() ).then(function (response) {
if(response.status == 200)
{
return cache.put(request, response);
}
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment