-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
54 lines (49 loc) · 1.64 KB
/
Copy pathsw.js
File metadata and controls
54 lines (49 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Minimal service worker for the hosted-PWA build mode. Its only jobs:
// 1. Satisfy the browser's PWA install criteria (must have a registered
// SW with a fetch handler).
// 2. Cache the navigation response so the chrome reloads without the
// network when the user opens the installed PWA offline.
//
// Hashed asset bundles get their own cache identity automatically since
// the URL changes on every deploy; we never serve a stale asset, just
// fall back to whatever's cached when fetch fails. The HTML cache is
// trimmed to the single latest navigation entry to avoid unbounded
// growth.
const NAV_CACHE = "obby-hosted-nav-v1";
self.addEventListener("install", () => {
self.skipWaiting();
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches
.keys()
.then((names) =>
Promise.all(
names.filter((name) => name !== NAV_CACHE).map((name) => caches.delete(name)),
),
)
.then(() => self.clients.claim()),
);
});
self.addEventListener("fetch", (event) => {
const req = event.request;
if (req.method !== "GET") return;
if (req.mode === "navigate") {
// Network-first: always try the live network so a fresh deploy is
// picked up immediately. Cache the response for the offline path.
event.respondWith(
fetch(req)
.then((res) => {
const copy = res.clone();
caches.open(NAV_CACHE).then((c) => c.put("/", copy));
return res;
})
.catch(() =>
caches
.open(NAV_CACHE)
.then((c) => c.match("/").then((r) => r || Response.error())),
),
);
return;
}
});