aboutsummaryrefslogtreecommitdiff
path: root/assets/sw.js
diff options
context:
space:
mode:
Diffstat (limited to 'assets/sw.js')
-rw-r--r--assets/sw.js54
1 files changed, 54 insertions, 0 deletions
diff --git a/assets/sw.js b/assets/sw.js
new file mode 100644
index 0000000..d7d517a
--- /dev/null
+++ b/assets/sw.js
@@ -0,0 +1,54 @@
+const cacheName = self.location.pathname
+const pages = [
+ {{ range .Site.AllPages -}}
+ "{{ .RelPermalink }}",
+ {{ end }}
+];
+
+self.addEventListener("install", function (event) {
+ self.skipWaiting();
+
+ const precache = caches.open(cacheName).then((cache) => {
+ return cache.addAll(pages);
+ });
+ event.waitUntil(precache);
+});
+
+self.addEventListener("fetch", (event) => {
+ const request = event.request;
+ if (request.method !== "GET") {
+ return;
+ }
+
+ /**
+ * @param {Response} response
+ * @returns {Promise<Response>}
+ */
+ function saveToCache(response) {
+ if (cacheable(response)) {
+ return caches
+ .open(cacheName)
+ .then((cache) => cache.put(request, response.clone()))
+ .then(() => response);
+ } else {
+ return response;
+ }
+ }
+
+ /**
+ * @param {Error} error
+ */
+ function serveFromCache(error) {
+ return caches.open(cacheName).then((cache) => cache.match(request.url));
+ }
+
+ /**
+ * @param {Response} response
+ * @returns {Boolean}
+ */
+ function cacheable(response) {
+ return response.type === "basic" && response.ok && !response.headers.has("Content-Disposition")
+ }
+
+ event.respondWith(fetch(request).then(saveToCache).catch(serveFromCache));
+});