Created
August 27, 2018 10:05
-
-
Save oscarotero/5c5218d6d66780e97f9bfd5464dddfd8 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
const version = 'v1'; | |
self.addEventListener('install', function(event) { | |
event.waitUntil( | |
caches.open(version).then(function(cache) { | |
return cache.addAll(['/sin-conexion']); | |
}) | |
); | |
}); | |
self.addEventListener('fetch', function(event) { | |
//Ignore piwik and non-GET requests | |
if (event.request.method !== 'GET' || ('' + event.request.url).indexOf('piwik.php') !== -1) { | |
return; | |
} | |
const destination = event.request.destination; | |
switch (destination) { | |
case 'style': | |
case 'script': | |
case 'image': | |
case 'font': | |
event.respondWith(assets(event.request)); | |
return; | |
default: | |
event.respondWith(pages(event.request)); | |
return; | |
} | |
}); | |
//Assets - cache first strategy | |
function assets(request) { | |
return caches.match(request).then(cached => { | |
if (cached !== undefined) { | |
return cached; | |
} | |
return fetch(request) | |
.catch(errorResponse) | |
.then(saveCache(request, 'assets')); | |
}); | |
} | |
//Html pages - network first strategy | |
function pages(request) { | |
return fetch(request) | |
.then(saveCache(request, 'pages')) | |
.catch(() => | |
caches.match(request).then(cached => { | |
if (cached !== undefined) { | |
return cached; | |
} | |
return errorResponse(); | |
}) | |
); | |
} | |
function saveCache(request, type) { | |
return function(response) { | |
const clonedResponse = response.clone(); | |
caches.open(`${version}-${type}`).then(function(cache) { | |
cache.put(request, clonedResponse); | |
}); | |
return response; | |
}; | |
} | |
function errorResponse() { | |
return caches.match('/sin-conexion').then(cached => { | |
return ( | |
cached || | |
new Response('Parece que no tienes internet', { | |
status: 503, | |
statusText: 'Service Unavailable' | |
}) | |
); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment