Skip to content

Commit 0fa1e1a

Browse files
committed
Corrected and improved service worker
1 parent 6075b6a commit 0fa1e1a

File tree

1 file changed

+25
-9
lines changed

1 file changed

+25
-9
lines changed

src/service-worker.js

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,19 +14,33 @@ import { build, files, version } from "$service-worker";
1414
const CACHE = `cache-${version}`;
1515

1616
/** @type {string[]} */
17-
const ASSETS = Array.from(new Set([...build, ...files, "/offline.html"]));
17+
const ASSETS = Array.from(
18+
new Set(
19+
[...build, ...files, "/offline.html"].filter(
20+
(path) =>
21+
!path.startsWith("http") &&
22+
!path.includes("licdn.com") &&
23+
!path.includes("googletagmanager.com"), // add others here if needed
24+
),
25+
),
26+
);
1827

19-
console.log("[SW] Assets to cache:", ASSETS); // Helps debug duplicates
28+
console.log("[SW] Assets to precache:", ASSETS); // Helps debug duplicates
2029

2130
/**
2231
* @param {ExtendableEvent} event
2332
*/
2433
sw.addEventListener("install", (event) => {
25-
/** @type {ExtendableEvent} */ (event).waitUntil(
26-
caches
27-
.open(CACHE)
28-
.then((cache) => cache.addAll(ASSETS))
29-
.then(() => sw.skipWaiting()),
34+
event.waitUntil(
35+
(async () => {
36+
const cache = await caches.open(CACHE);
37+
try {
38+
await cache.addAll(ASSETS);
39+
sw.skipWaiting();
40+
} catch (err) {
41+
console.warn("[SW] Failed to precache some assets:", err);
42+
}
43+
})(),
3044
);
3145
});
3246

@@ -64,8 +78,10 @@ sw.addEventListener("activate", (event) => {
6478
sw.addEventListener("fetch", (event) => {
6579
/** @type {FetchEvent} */ (event).respondWith(
6680
(async () => {
67-
const cached = await caches.match(event.request);
68-
if (cached) return cached;
81+
if (new URL(event.request.url).origin === location.origin) {
82+
const cached = await caches.match(event.request);
83+
if (cached) return cached;
84+
}
6985

7086
try {
7187
if (event.request.mode === "navigate") {

0 commit comments

Comments
 (0)