-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
86 lines (76 loc) · 2.05 KB
/
Copy pathsw.js
File metadata and controls
86 lines (76 loc) · 2.05 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
82
83
84
85
86
const CACHE_PREFIX = 'jal-sathi';
const CACHE = `${CACHE_PREFIX}-v2026-03-19`;
const APP_SHELL = [
'./',
'./index.html',
'./styles.css',
'./app.js',
'./manifest.json',
'./logo.svg',
'./favicon.svg',
'./about.html',
'./resources.html',
'./contact.html',
'./privacy-policy.html',
'./terms.html',
'./notification-prompt.js'
];
self.addEventListener('install', (event) => {
event.waitUntil(caches.open(CACHE).then((cache) => cache.addAll(APP_SHELL)));
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(
keys
.filter((key) => key.startsWith(`${CACHE_PREFIX}-`) && key !== CACHE)
.map((key) => caches.delete(key))
)
)
);
self.clients.claim();
});
self.addEventListener('message', (event) => {
if (event.data?.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
self.addEventListener('fetch', (event) => {
const { request } = event;
if (request.method !== 'GET') return;
const url = new URL(request.url);
if (url.origin !== self.location.origin) return;
if (request.mode === 'navigate') {
event.respondWith(networkFirst(request, './index.html'));
return;
}
if (APP_SHELL.some((asset) => url.pathname.endsWith(asset.replace('./', '/')))) {
event.respondWith(staleWhileRevalidate(request));
}
});
async function networkFirst(request, fallbackAsset) {
const cache = await caches.open(CACHE);
try {
const response = await fetch(request);
if (response.ok) {
cache.put(request, response.clone());
}
return response;
} catch (error) {
return (await cache.match(request)) || (await cache.match(fallbackAsset));
}
}
async function staleWhileRevalidate(request) {
const cache = await caches.open(CACHE);
const cached = await cache.match(request);
const fresh = fetch(request)
.then((response) => {
if (response.ok) {
cache.put(request, response.clone());
}
return response;
})
.catch(() => cached);
return cached || fresh;
}