diff options
author | Alex Shpak <alex-shpak@users.noreply.github.com> | 2020-04-12 20:50:03 +0200 |
---|---|---|
committer | Alex Shpak <alex-shpak@users.noreply.github.com> | 2020-04-12 20:50:03 +0200 |
commit | 9719692512325b5f88de666281ba286343408010 (patch) | |
tree | 2551be94373e26f668f8756bee493c9b11ee48e0 /static | |
parent | e4e43bd9b12a3e37f0d3c2760ea7f867ba8273a7 (diff) |
Introduce serviceWorker, disabled by default
Diffstat (limited to 'static')
-rw-r--r-- | static/sw.js | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/static/sw.js b/static/sw.js new file mode 100644 index 0000000..d42b04c --- /dev/null +++ b/static/sw.js @@ -0,0 +1,44 @@ +self.addEventListener("install", function (event) { + self.skipWaiting(); +}); + +self.addEventListener("fetch", (event) => { + const cacheName = self.location.pathname + 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)); +}); |