-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice-worker.js
More file actions
61 lines (56 loc) · 1.74 KB
/
service-worker.js
File metadata and controls
61 lines (56 loc) · 1.74 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
const CACHE_NAME = 'samsanders-cache-v2';
const ASSETS = [
'/',
'/index.html',
'/manifest.json',
'/favicon-32x32.png',
'/favicon-16x16.png',
'/apple-touch-icon.png',
'/android-chrome-192x192.png',
'/android-chrome-512x512.png',
'/images/portrait.webp',
'/images/portrait.jpg',
'/robots.txt',
'/sitemap.xml',
'/security.txt',
'/.well-known/security.txt'
];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME).then(cache => cache.addAll(ASSETS))
);
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)))
).then(() => clients.claim())
);
});
self.addEventListener('fetch', event => {
if (event.request.method !== 'GET') return;
const requestURL = new URL(event.request.url);
// Same-origin static assets: cache-first
if (requestURL.origin === location.origin && (
requestURL.pathname.startsWith('/images/') ||
requestURL.pathname.endsWith('.woff2') ||
requestURL.pathname.endsWith('.png') ||
requestURL.pathname.endsWith('.jpg') ||
requestURL.pathname.endsWith('.webp') ||
requestURL.pathname.endsWith('.json')
)) {
event.respondWith(
caches.match(event.request).then(cached => cached || fetch(event.request).then(networkRes => {
const copy = networkRes.clone();
caches.open(CACHE_NAME).then(c => c.put(event.request, copy));
return networkRes;
})).catch(() => caches.match('/images/portrait.webp'))
);
return;
}
// Default: network-first, fallback to cache
event.respondWith(
fetch(event.request).then(res => res).catch(() => caches.match(event.request))
);
});