Last active
July 27, 2016 18:48
-
-
Save rubys/8b871ce0f0c663a4b8a62d561d58afc6 to your computer and use it in GitHub Desktop.
ASF Board Agenda service worker
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
// | |
// A very simple service worker | |
// | |
// 1) Create an event source and pass all events received to all clients | |
// | |
// 2) Return back cached bootstrap page instead of fetching agenda pages | |
// from the network. Bootstrap will construct page from cached | |
// agenda.json, as well as update the cache. | |
// | |
// 3) For all other pages, serve cached content when offline | |
// | |
var events = null; | |
this.addEventListener("activate", function(event) { | |
// close any pre-existing event socket | |
if (events) { | |
try { | |
events.close() | |
} catch (e) { | |
events = null | |
} | |
}; | |
// create a new event source | |
events = new EventSource("events"); | |
// dispatch any events received to clients | |
events.addEventListener("message", function(event) { | |
clients.matchAll().then(function(list) { | |
list.forEach(function(client) { | |
client.postMessage(event.data) | |
}) | |
}) | |
}) | |
}); | |
this.addEventListener("fetch", function(event) { | |
var scope = this.registration.scope; | |
var url = event.request.url; | |
if (url.substring(0, scope.length) == scope) url = url.slice(scope.length); | |
if (new RegExp("^\\d\\d\\d\\d-\\d\\d-\\d\\d/").test(url) && event.request.method == "GET") { | |
event.respondWith(caches.open("board/agenda").then(function(cache) { | |
var date = url.split("/")[0]; | |
return cache.match(date + "/bootstrap.html").then(function(response) { | |
return response || fetch(event.request.url, {credentials: "include"}) | |
}) | |
})) | |
} else { | |
event.respondWith(fetch(event.request, {credentials: "include"}).catch(function(error) { | |
return caches.open("board/agenda").then(function(cache) { | |
return cache.match(event.request, function(response) { | |
return response || error | |
}) | |
}) | |
})) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment