Created
October 2, 2017 17:38
-
-
Save UnJavaScripter/a3c5c9f24b2084ee58f96f3319cd4734 to your computer and use it in GitHub Desktop.
A demo service worker file
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 CACHE_ACTUAL = 'cache'; | |
const archivos_para_cachear = [ | |
'/', | |
'/?launcher=true', | |
'/main.js', | |
'/styles.css', | |
'/assets/logo.png' | |
]; | |
// Instalación del service worker y cacheo inicial | |
self.addEventListener('install', (event) => { | |
event.waitUntil(caches.open(CACHE_ACTUAL) | |
.then((cache) => { | |
return cache.addAll(archivos_para_cachear).then(() => { | |
console.log('Archivos cacheados'); | |
}); | |
}) | |
.then((_) => { return self.skipWaiting(); })); | |
}); | |
// El service worker actual tomó control | |
self.addEventListener('activate', (event) => { | |
event.waitUntil(self.clients.claim()); | |
event.waitUntil(caches.keys().then((lasCachesQueExisten) => { | |
return Promise.all(lasCachesQueExisten.map((unaCache) => { | |
if (unaCache !== CACHE_ACTUAL) { | |
return caches["delete"](unaCache).then(() => { | |
console.log('Cachés previas eliminadas'); | |
}); | |
} | |
})); | |
})); | |
}); | |
// Interceptor de solicitudes | |
self.addEventListener('fetch', (event) => { | |
event.respondWith(caches.match(event.request) | |
.then((respuestaEnCache) => { | |
const laSolicitud = event.request.clone(); | |
return fetch(laSolicitud).then((respuestaDeLaRed) => { | |
if (!respuestaDeLaRed | |
|| respuestaDeLaRed.status !== 200 | |
|| respuestaDeLaRed.type !== 'basic' | |
|| (/(google-analytics.com)|(fonts.googleapis.com)/gi).test(laSolicitud.url)) { | |
return respuestaDeLaRed; | |
} | |
const respuestaDeLaRedParaCachear = respuestaDeLaRed.clone(); | |
caches.open(CACHE_ACTUAL) | |
.then((cache) => { | |
cache.put(event.request, respuestaDeLaRedParaCachear); | |
}); | |
return respuestaDeLaRed; | |
})["catch"]((err) => { | |
return respuestaEnCache; | |
}); | |
})); | |
}); | |
// Notificaciones Push | |
self.addEventListener('push', (event) => { | |
const title = 'Jojojo'; | |
const body = '¡Un mensaje Push ha llegado!'; | |
const icon = '/apple-touch-icon.png'; | |
const tag = 'jojojojojo-push-tag'; | |
event.waitUntil(self.registration.showNotification(title, { | |
body: body, | |
icon: icon, | |
tag: tag | |
})); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment