Created
July 16, 2016 20:59
-
-
Save justmarkup/4e55b392652fe364ff4c6a8a2c004602 to your computer and use it in GitHub Desktop.
simple service worker for reveal.js
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
<script> | |
if (navigator.serviceWorker) { | |
navigator.serviceWorker.register('./serviceworker.js', { | |
scope: './' | |
}); | |
} | |
</script> |
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::'; | |
self.addEventListener("fetch", function(event) { | |
if (event.request.method !== 'GET') { | |
return; | |
} | |
event.respondWith( | |
caches | |
.match(event.request) | |
.then(function(cached) { | |
var networked = fetch(event.request) | |
.then(fetchedFromNetwork, unableToResolve) | |
.catch(unableToResolve); | |
return cached || networked; | |
function fetchedFromNetwork(response) { | |
var cacheCopy = response.clone(); | |
caches | |
.open(version + 'pages') | |
.then(function add(cache) { | |
cache.put(event.request, cacheCopy); | |
}); | |
return response; | |
} | |
function unableToResolve () { | |
return new Response('<h1>Service Unavailable</h1>', { | |
status: 503, | |
statusText: 'Service Unavailable', | |
headers: new Headers({ | |
'Content-Type': 'text/html' | |
}) | |
}); | |
} | |
}) | |
); | |
}); | |
self.addEventListener("activate", function(event) { | |
event.waitUntil( | |
caches | |
.keys() | |
.then(function (keys) { | |
return Promise.all( | |
keys | |
.filter(function (key) { | |
return !key.startsWith(version); | |
}) | |
.map(function (key) { | |
return caches.delete(key); | |
}) | |
); | |
}) | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment