-
Notifications
You must be signed in to change notification settings - Fork 161
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Meta: add a service worker to the spec #637
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
747de91
Meta: add a service worker to the spec
domenic bd4c976
Switch to a network-then-cache strategy
domenic 8864ed6
Add web app manifest
domenic aef12ab
Temporary commit for better testing
domenic b26845f
Revert "Add web app manifest"
domenic 2ad9488
Do cache-then-network for everything but the main resource
domenic f2919bd
Add appropriate waitUntils + Jake's polyfill
domenic 82a111c
Revert "Temporary commit for better testing"
domenic File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4308,3 +4308,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> |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,113 @@ | ||
"use strict"; | ||
|
||
const cacheKey = "v2"; | ||
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; | ||
} | ||
|
||
if (needsToBeFresh(e.request)) { | ||
// Since this is a Living Standard, it is imperative that you see the freshest content, so we use a | ||
// network-then-cache strategy for the main content. | ||
e.respondWith( | ||
fetch(e.request).then(res => { | ||
e.waitUntil(refreshCacheFromNetworkResponse(e.request, res)); | ||
return res; | ||
}) | ||
.catch(() => { | ||
return caches.match(e.request); | ||
}) | ||
); | ||
} else { | ||
// For auxiliary resources, we can use a cache-then-network strategy; it is OK to not get the freshest. | ||
e.respondWith( | ||
caches.match(e.request).then(cachedResponse => { | ||
const networkFetchPromise = fetch(e.request); | ||
|
||
// Ignore network fetch or caching errors; they just mean we won't be able to refresh the cache. | ||
e.waitUntil( | ||
networkFetchPromise | ||
.then(res => refreshCacheFromNetworkResponse(e.request, res)) | ||
.catch(() => {}) | ||
); | ||
|
||
return cachedResponse || networkFetchPromise; | ||
}) | ||
); | ||
} | ||
}; | ||
|
||
self.onactivate = e => { | ||
e.waitUntil(caches.keys().then(keys => { | ||
return Promise.all(keys.filter(key => key !== cacheKey).map(key => caches.delete(key))); | ||
})); | ||
}; | ||
|
||
function refreshCacheFromNetworkResponse(req, res) { | ||
if (!res.ok) { | ||
throw new Error(`${res.url} is responding with ${res.status}`); | ||
} | ||
|
||
const resForCache = res.clone(); | ||
|
||
return caches.open(cacheKey).then(cache => cache.put(req, resForCache)); | ||
} | ||
|
||
function needsToBeFresh(req) { | ||
const requestURL = new URL(req.url); | ||
return requestURL.origin === location.origin && requestURL.pathname === "/"; | ||
} | ||
|
||
// From https://github.com/jakearchibald/async-waituntil-polyfill | ||
// Apache 2 License: https://github.com/jakearchibald/async-waituntil-polyfill/blob/master/LICENSE | ||
{ | ||
const waitUntil = ExtendableEvent.prototype.waitUntil; | ||
const respondWith = FetchEvent.prototype.respondWith; | ||
const promisesMap = new WeakMap(); | ||
|
||
ExtendableEvent.prototype.waitUntil = function(promise) { | ||
const extendableEvent = this; | ||
let promises = promisesMap.get(extendableEvent); | ||
|
||
if (promises) { | ||
promises.push(Promise.resolve(promise)); | ||
return; | ||
} | ||
|
||
promises = [Promise.resolve(promise)]; | ||
promisesMap.set(extendableEvent, promises); | ||
|
||
// call original method | ||
return waitUntil.call(extendableEvent, Promise.resolve().then(function processPromises() { | ||
const len = promises.length; | ||
|
||
// wait for all to settle | ||
return Promise.all(promises.map(p => p.catch(()=>{}))).then(() => { | ||
// have new items been added? If so, wait again | ||
if (promises.length != len) return processPromises(); | ||
// we're done! | ||
promisesMap.delete(extendableEvent); | ||
// reject if one of the promises rejected | ||
return Promise.all(promises); | ||
}); | ||
})); | ||
}; | ||
|
||
FetchEvent.prototype.respondWith = function(promise) { | ||
this.waitUntil(promise); | ||
return respondWith.call(this, promise); | ||
}; | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm guessing this will be the only service worker on this origin? A more general solution might not be able to assume this.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yep :)