Skip to content

Commit

Permalink
Meta: add a service worker to the spec
Browse files Browse the repository at this point in the history
This allows the spec to be viewed offline.
  • Loading branch information
domenic committed Dec 29, 2016
1 parent 68aa48c commit 7e7832e
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
1 change: 1 addition & 0 deletions deploy.sh
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ else
> $WEB_ROOT/index.intermediate.html
node_modules/.bin/emu-algify --throwing-indicators < $WEB_ROOT/index.intermediate.html > $WEB_ROOT/index.html
rm $WEB_ROOT/index.intermediate.html
cp service-worker.js $WEB_ROOT/service-worker.js
echo "Living standard output to $WEB_ROOT"
fi

Expand Down
7 changes: 7 additions & 0 deletions index.bs
Original file line number Diff line number Diff line change
Expand Up @@ -4314,3 +4314,10 @@ This standard is written by <a href="https://domenic.me/">Domenic Denicola</a>
<a href="mailto:[email protected]">[email protected]</a>).

Per <a href="https://creativecommons.org/publicdomain/zero/1.0/">CC0</a>, to the extent possible under law, the editor has waived all copyright and related or neighboring rights to this work.

<script>
"use strict";
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("service-worker.js");
}
</script>
47 changes: 47 additions & 0 deletions service-worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"use strict";
// Largely based on https://css-tricks.com/serviceworker-for-offline/

const cacheKey = "v1";
const toCache = [
"/",
"https://resources.whatwg.org/standard.css",
"https://resources.whatwg.org/bikeshed.css",
"https://resources.whatwg.org/file-issue.js",
"https://resources.whatwg.org/commit-snapshot-shortcut-key.js",
"https://resources.whatwg.org/logo-streams.svg"
];

self.oninstall = e => {
e.waitUntil(caches.open(cacheKey).then(cache => cache.addAll(toCache)));
};

self.onfetch = e => {
if (e.request.method !== "GET") {
return;
}

e.respondWith(
caches.match(e.request).then(cachedResponse => {
// Respond with the cached response if it exists, but still do the network fetch in order to refresh the cache.
// Ignore network fetch errors; they just mean we won't be able to cache.
const networkFetchPromise = fetch(e.request).then(refreshCacheFromNetworkResponse).catch(() => {});

return cachedResponse || networkFetchPromise;
})
);

function refreshCacheFromNetworkResponse(response) {
const responseForCache = response.clone();

// Ignore any errors while caching.
caches.open(cacheKey).then(cache => cache.put(e.request, responseForCache));

return response;
}
};

self.onactivate = e => {
e.waitUntil(caches.keys().then(keys => {
return Promise.all(keys.filter(key => key !== cacheKey).map(key => caches.delete(key)));
}));
};

0 comments on commit 7e7832e

Please sign in to comment.