Created
February 24, 2019 20:47
-
-
Save hcastillaq/1cb6b210277bf6174163cffb0ab938af 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
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