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 1526b35
Showing 1 changed file with 26 additions and 21 deletions.
47 changes: 26 additions & 21 deletions assets/sw.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,30 @@
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 cacheFirst(request) {
const cached = await caches.match(request);
if (cached) {
return cached;
}

try {
const res = await fetch(request);
if (res.ok) {
const cache = await caches.open(cacheName);
cache.put(request, res.clone());
}
return res;
} catch (error) {
return 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);
console.log(event.request.destination);
if (url.pathname.match(cachePath)) {
event.respondWith(cacheFirst(event.request));
}
});

0 comments on commit 1526b35

Please sign in to comment.