Service Worker to make the site offline
var version = 'v1::'; | |
// ------------------------------------------------------- | |
// aqui devem ser baixados os recursos offline, que devem vir de uma lista em algum local | |
// provavelmente alguma API no site | |
this.addEventListener('install', function(event) { | |
console.log('Service Worker instalado!'); | |
// return self.clients.skipWaiting(); | |
}); | |
this.addEventListener('activate', function(event) { | |
console.log('Service worker ativado!'); | |
return self.clients.claim(); | |
}); | |
this.addEventListener('fetch', function(event) { | |
event.respondWith( | |
caches.match(event.request).then(function(response) { | |
return response || fetch(event.request); | |
}).catch(function(error) { | |
console.log(event.request.url, error); | |
}) | |
); | |
}); | |
this.addEventListener('message', function(event) { | |
// ------------------------------------------------------- | |
// this is a function called when the 'refresh offline site' its called | |
if (event.data.action === 'update') { | |
caches.keys().then(function(keys) { | |
return Promise.all(keys.map(function(key) { | |
return caches.delete(keys[key]); | |
})); | |
}); | |
// this endpoint returns all URLs and imagens that must me cached | |
fetch('/ajax/offline', {mode: 'no-cors', cache: 'no-cache'}).then(function(response) { | |
return response.json(); | |
}).then(function(resources) { | |
return caches.open(version).then(function(cache) { | |
return cache.addAll(resources); | |
}); | |
}).then(function() { | |
event.ports[0].postMessage({completed: true}); | |
console.log('cache atualzado!'); | |
}); | |
} | |
// ------------------------------------------------------- | |
// clearing the cache | |
if (event.data.action === 'clear') { | |
caches.keys().then(function(keys) { | |
return Promise.all(keys.map(function(key) { | |
return caches.delete(keys[key]); | |
})); | |
}).then(function() { | |
event.ports[0].postMessage({completed: true}); | |
console.log('cache limpo!'); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment