summaryrefslogtreecommitdiff
path: root/public/sw2.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/sw2.js
Initial commit
Diffstat (limited to 'public/sw2.js')
-rw-r--r--public/sw2.js40
1 files changed, 40 insertions, 0 deletions
diff --git a/public/sw2.js b/public/sw2.js
new file mode 100644
index 0000000..a778887
--- /dev/null
+++ b/public/sw2.js
@@ -0,0 +1,40 @@
+// https://googlechrome.github.io/samples/service-worker/basic/
+
+const PRECACHE = "wordly-precache-v1";
+const RUNTIME = "wordly-runtime";
+
+const PRECACHE_URLS = [
+ "./", // Alias for index.html
+ "index.html",
+ "style.css",
+ "main.js"
+];
+
+self.addEventListener("install", e => e.waitUntil(
+ caches.open(PRECACHE)
+ .then(cache => cache.addAll(PRECACHE_URLS))
+ .then(self.skipWaiting())));
+
+self.addEventListener("activate", e => {
+ const currentCaches = [PRECACHE, RUNTIME];
+ e.waitUntil( // Clean up old caches
+ caches.keys().then(cacheNames =>
+ cacheNames.filter(cacheName => !currentCaches.includes(cacheName))
+ ).then(cachesToDelete => Promise.all(cachesToDelete.map(cacheToDelete =>
+ caches.delete(cacheToDelete)))
+ ).then(() => self.clients.claim())
+ );
+});
+
+self.addEventListener("fetch", e => {
+ if (e.request.url.startsWith(self.location.origin)) {
+ e.respondWith(caches.match(e.request).then(cachedResponse =>
+ cachedResponse? cachedResponse
+ : caches.open(RUNTIME).then(cache =>
+ fetch(e.request).then(res =>
+ cache.put(e.request, res.clone()).then(() => res)
+ )
+ )
+ ));
+ }
+});