hugo-book/assets/sw.js

56 lines
1.2 KiB
JavaScript
Raw Normal View History

2020-04-21 20:35:30 +00:00
const cacheName = self.location.pathname
const pages = [
2020-05-01 15:45:23 +00:00
{{ if eq .Site.Params.BookServiceWorker "precache" }}
2020-04-21 20:35:30 +00:00
{{ range .Site.AllPages -}}
"{{ .RelPermalink }}",
2020-05-01 15:45:23 +00:00
{{ end -}}
{{ end }}
2020-04-21 20:35:30 +00:00
];
self.addEventListener("install", function (event) {
self.skipWaiting();
2020-04-21 20:35:30 +00:00
2020-05-01 15:35:08 +00:00
caches.open(cacheName).then((cache) => {
2020-04-21 20:35:30 +00:00
return cache.addAll(pages);
});
});
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));
});