Last active
August 30, 2016 11:58
-
-
Save luisdalmolin/1e8cf8ac2d13dce2c0f7083a93feac89 to your computer and use it in GitHub Desktop.
Service Worker to make the site offline
This file contains hidden or 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
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