summaryrefslogtreecommitdiff
path: root/public/sw1.js
diff options
context:
space:
mode:
authorAlexis Hovorka <[email protected]>2022-02-02 00:06:53 -0700
committerAlexis Hovorka <[email protected]>2022-02-02 00:06:53 -0700
commit8a943500d97598a0b49ef655dc1b5484fe5e83d8 (patch)
tree339daf640084d724524c3cfcf92e51f48f7037b0 /public/sw1.js
Initial commit
Diffstat (limited to 'public/sw1.js')
-rw-r--r--public/sw1.js29
1 files changed, 29 insertions, 0 deletions
diff --git a/public/sw1.js b/public/sw1.js
new file mode 100644
index 0000000..5bf5a24
--- /dev/null
+++ b/public/sw1.js
@@ -0,0 +1,29 @@
+// https://gist.github.com/adactio/3717b7da007a9363ddf21f584aae34af
+
+// HTML files: try the network first, then the cache.
+// Other files: try the cache first, then the network.
+// Both: cache a fresh version if possible.
+// (beware: the cache will grow and grow; there's no cleanup)
+
+const cacheName = "wordly-cache-v1";
+
+addEventListener("fetch", fetchEvent => {
+ const request = fetchEvent.request;
+ if (request.method !== "GET") return;
+ fetchEvent.respondWith(async () => {
+ const fetchPromise = fetch(request);
+ fetchEvent.waitUntil(async () => {
+ const responseFromFetch = await fetchPromise;
+ const responseCopy = responseFromFetch.clone();
+ const myCache = await caches.open(cacheName);
+ return myCache.put(request, responseCopy);
+ }());
+ if (request.headers.get("Accept").includes("text/html")) {
+ try { return await fetchPromise; }
+ catch(error) { return caches.match(request); }
+ } else {
+ const responseFromCache = await caches.match(request);
+ return responseFromCache || fetchPromise;
+ }
+ }());
+});