Skip to content

Commit

Permalink
Fix offline
Browse files Browse the repository at this point in the history
  • Loading branch information
eero-lehtinen committed Oct 5, 2024
1 parent fb44d90 commit 08abded
Showing 1 changed file with 21 additions and 21 deletions.
42 changes: 21 additions & 21 deletions assets/sw.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
var cacheName = "oklch-color-picker-pwa";
var filesToCache = [
"./",
"./index.html",
"./oklch-color-picker.js",
"./oklch-color-picker_bg.wasm",
];

/* Start the service worker and cache all of the app's content */
self.addEventListener("install", function (e) {
e.waitUntil(
caches.open(cacheName).then(function (cache) {
return cache.addAll(filesToCache);
}),
);
});
async function networkFirst(request) {
try {
const networkResponse = await fetch(request);
if (networkResponse.ok) {
const cache = await caches.open(cacheName);
cache.put(request, networkResponse.clone());
}
return networkResponse;
} catch (error) {
const cachedResponse = await caches.match(request);
return cachedResponse || Response.error();
}
}

const cachePath =
/\/$|\/index\.html$|\/oklch-color-picker-(\w|\d)*\.js$|\/oklch-color-picker-(\w|\d)*_bg\.wasm$/;

/* Serve cached content when offline */
self.addEventListener("fetch", function (e) {
e.respondWith(
caches.match(e.request).then(function (response) {
return response || fetch(e.request);
}),
);
self.addEventListener("fetch", (event) => {
const url = new URL(event.request.url);
if (url.pathname.match(cachePath)) {
event.respondWith(networkFirst(event.request));
}
});

0 comments on commit 08abded

Please sign in to comment.