-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
74 lines (66 loc) · 2.58 KB
/
Copy pathsw.js
File metadata and controls
74 lines (66 loc) · 2.58 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Minimal service worker — exists mainly to satisfy PWA installability criteria.
// This app shows live team data, so it deliberately does NOT cache or serve HTML/API
// responses offline (that would risk showing stale projects/tasks/chat to someone who
// thinks they're online).
//
// Caching strategy split in two, because most assets here have no cache-busting hash
// or version query string:
// - CSS/JS: network-first. There's no build step, so a stale-while-revalidate here
// would mean edits lag by an extra reload — actively confusing during development
// and no real benefit in production either. Cache is only a fallback if offline.
// - Images/fonts: cache-first. These essentially never change after being added, so
// it's a safe, real performance win with no staleness risk worth worrying about.
const CACHE_NAME = 'workflow-static-v2';
const NETWORK_FIRST_RE = /\/assets\/(css|js)\//;
const CACHE_FIRST_RE = /\/assets\/(image|font)\//;
self.addEventListener('install', (event) => {
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k)))
)
);
self.clients.claim();
});
self.addEventListener('fetch', (event) => {
const req = event.request;
if (req.method !== 'GET') return;
const path = new URL(req.url).pathname;
if (NETWORK_FIRST_RE.test(path)) {
event.respondWith(
fetch(req)
.then((res) => {
// clone() has to happen synchronously, right here, before the response
// is returned and its body starts being consumed by the page -- doing
// it inside the caches.open().then() callback below (the old code) ran
// it after that consumption had already started, which is why it threw
// "Response body is already used" on effectively every asset load.
if (res.ok) {
const copy = res.clone();
caches.open(CACHE_NAME).then((c) => c.put(req, copy));
}
return res;
})
.catch(() => caches.match(req))
);
return;
}
if (CACHE_FIRST_RE.test(path)) {
event.respondWith(
caches.match(req).then((cached) => {
if (cached) return cached;
return fetch(req).then((res) => {
if (res.ok) {
const copy = res.clone();
caches.open(CACHE_NAME).then((c) => c.put(req, copy));
}
return res;
});
})
);
return;
}
// everything else (HTML, api_* endpoints): let the browser handle it normally
});