Skip to content

Instantly share code, notes, and snippets.

@evertonstrack
Created July 31, 2018 22:14
Show Gist options
  • Save evertonstrack/934d97612e46d19362c3a3a458c1f0aa to your computer and use it in GitHub Desktop.
Save evertonstrack/934d97612e46d19362c3a3a458c1f0aa to your computer and use it in GitHub Desktop.
service-wroker.js
// 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