Network-first cache in service worker

This commit is contained in:
Pavel Djundik 2018-06-05 15:28:09 +03:00
parent d5f0a2481f
commit 1f604a8556
1 changed files with 55 additions and 0 deletions

View File

@ -2,6 +2,61 @@
/* global clients */ /* global clients */
"use strict"; "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) { self.addEventListener("message", function(event) {
showNotification(event, event.data); showNotification(event, event.data);
}); });