service-wroker.js
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
// Criando um nome para o arquivo de cache | |
const staticCache = "meu-site-2018-07-31-21-13"; | |
// Lista de arquivos que devem ser cacheados | |
const files = [ | |
'/', | |
'/sobre', | |
'/contato', | |
'/images/logo.jpg', | |
'/assets/styles/main.min.css', | |
'/assets/scripts/main.min.js', | |
]; | |
// Faz cache dos arquivos ao instalar | |
this.addEventListener("install", event => { | |
this.skipWaiting(); | |
event.waitUntil( | |
caches.open(staticCache) | |
.then(cache => { | |
return cache.addAll(files); | |
}) | |
) | |
}); | |
// Limpa o cache antigo | |
this.addEventListener('activate', event => { | |
event.waitUntil( | |
caches.keys().then(cacheNames => { | |
return Promise.all( | |
cacheNames | |
.filter(cacheName => (cacheName.startsWith('meu-site-'))) | |
.filter(cacheName => (cacheName !== staticCache)) | |
.map(cacheName => caches.delete(cacheName)) | |
); | |
}) | |
); | |
}); | |
// Reponde o request direto do cache | |
this.addEventListener("fetch", event => { | |
event.respondWith( | |
caches.match(event.request) | |
.then(response => { | |
// Retorna o cache | |
if (response) { | |
return response; | |
} | |
// Faz a requisição | |
return fetch(event.request); | |
}) | |
.catch(() => { | |
// Mostra uma página de offline | |
return caches.match('/offline.html'); | |
}) | |
) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment