- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
Latest commit
59 lines (51 loc) · 1.62 KB
/
Copy pathsw.js
File metadata and controls
59 lines (51 loc) · 1.62 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
varcacheName='ezchat-v1';
varfilesToCache=[
'./',
'./index.html',
'./ezchat.js',
'./ezchat_bg.wasm',
];
/* Start the service worker and cache all of the app's content */
self.addEventListener('install',(e)=>{
e.waitUntil((async()=>{
constcache=awaitcaches.open(cacheName);
awaitPromise.allSettled(filesToCache.map(async(url)=>{
try{
constres=awaitfetch(url,{cache: 'no-store'});
if(!res.ok)thrownewError(`${res.status}${res.statusText}`);
awaitcache.put(url,res);
}catch(err){
console.info('[SW] precache failed:',url,err);
}
}));
awaitself.skipWaiting();
})());
});
/* Clean up outdated caches and take control of all clients immediately */
self.addEventListener('activate',(e)=>{
e.waitUntil((async()=>{
constkeys=awaitcaches.keys();
awaitPromise.all(keys.map((k)=>(k!==cacheName ? caches.delete(k) : Promise.resolve())));
awaitself.clients.claim();
})());
})
/* Serve cached content when offline */
self.addEventListener('fetch',(e)=>{
consturl=newURL(e.request.url);
constscope=newURL(self.registration.scope);
if(url.origin!==scope.origin)return;
if(e.request.method!=='GET')return;
e.respondWith((async()=>{
constcached=awaitcaches.match(e.request);
if(cached)returncached;
try{
returnawaitfetch(e.request);
}catch(err){
if(e.request.mode==='navigate'){
constfallback=awaitcaches.match('./index.html');
if(fallback)returnfallback;
}
returnResponse.error();
}
})());
});