From 1f604a8556c21747f6d4986996cc927915c8bf0e Mon Sep 17 00:00:00 2001 From: Pavel Djundik Date: Tue, 5 Jun 2018 15:28:09 +0300 Subject: [PATCH] Network-first cache in service worker --- client/service-worker.js | 55 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/client/service-worker.js b/client/service-worker.js index cd0af83f..261550cc 100644 --- a/client/service-worker.js +++ b/client/service-worker.js @@ -2,6 +2,61 @@ /* global clients */ "use strict"; +const excludedPathsFromCache = /^(?:socket\.io|storage|uploads|cdn-cgi)\//; + +self.addEventListener("install", function() { + self.skipWaiting(); +}); + +self.addEventListener("activate", function(event) { + event.waitUntil(self.clients.claim()); +}); + +self.addEventListener("fetch", function(event) { + if (event.request.method !== "GET") { + return; + } + + const url = event.request.url; + const scope = self.registration.scope; + + // Skip cross-origin requests + if (!url.startsWith(scope)) { + return; + } + + const path = url.substring(scope.length); + + // Skip ignored paths + if (excludedPathsFromCache.test(path)) { + return; + } + + const uri = new URL(url); + uri.hash = ""; + uri.search = ""; + + event.respondWith(networkOrCache(uri)); +}); + +function networkOrCache(uri) { + return caches.open("thelounge").then(function(cache) { + return fetch(uri) + .then(function(response) { + if (response.ok) { + return cache.put(uri, response.clone()).then(function() { + return response; + }); + } + }) + .catch(function() { + return cache.match(uri).then(function(matching) { + return matching || Promise.reject("request-not-in-cache"); + }); + }); + }); +} + self.addEventListener("message", function(event) { showNotification(event, event.data); });