-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
82 lines (74 loc) · 2.23 KB
/
Copy pathsw.js
File metadata and controls
82 lines (74 loc) · 2.23 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
75
76
77
78
79
80
81
const CACHE_VERSION = 'np-v1';
const STATIC_CACHE = `${CACHE_VERSION}-static`;
const CONTENT_CACHE = `${CACHE_VERSION}-content`;
const PRECACHE_ASSETS = [
'/',
'/assets/css/tokens.css',
'/assets/css/global.css',
'/assets/css/components.css',
'/assets/js/nav.js',
'/assets/js/copy-button.js',
'/assets/js/accordions.js',
'/assets/js/checkboxes.js',
'/assets/js/tables.js',
'/assets/img/logo.svg',
'/manifest.json',
];
// Install — pre-cache shell assets
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(STATIC_CACHE).then((cache) => cache.addAll(PRECACHE_ASSETS))
);
self.skipWaiting();
});
// Activate — clean up old caches
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(
keys
.filter((k) => k.startsWith('np-') && k !== STATIC_CACHE && k !== CONTENT_CACHE)
.map((k) => caches.delete(k))
)
)
);
self.clients.claim();
});
// Fetch strategy
self.addEventListener('fetch', (event) => {
const { request } = event;
const url = new URL(request.url);
// Only handle same-origin requests
if (url.origin !== location.origin) return;
const isHtml = request.headers.get('accept')?.includes('text/html');
const isStatic = /\.(css|js|svg|png|ico|woff2?|webp|jpg|jpeg|gif|webmanifest|json)$/.test(url.pathname);
if (isStatic) {
// Cache-first for static assets
event.respondWith(
caches.match(request).then((cached) => {
if (cached) return cached;
return fetch(request).then((response) => {
if (response.ok) {
const clone = response.clone();
caches.open(STATIC_CACHE).then((c) => c.put(request, clone));
}
return response;
});
})
);
} else if (isHtml) {
// Network-first (stale-while-revalidate) for HTML pages
event.respondWith(
caches.open(CONTENT_CACHE).then(async (cache) => {
try {
const response = await fetch(request);
if (response.ok) cache.put(request, response.clone());
return response;
} catch {
const cached = await cache.match(request);
return cached || caches.match('/');
}
})
);
}
});