-
Notifications
You must be signed in to change notification settings - Fork 0
/
service-worker.min.js
62 lines (44 loc) · 1.65 KB
/
service-worker.min.js
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
const cacheName = 'v4';
const cachedItems = [
"/",
"/index.html",
"/css/worker.css",
"/js/index.js",
];
const addCache = async (resources) => {//cache on install event
console.log('installed');
const cache = await caches.open(cacheName );
await cache.addAll(resources);
};
const putNewCache = async (req, res) => { //cache on fetch event
const cache = await caches.open(cacheName);
await cache.put(req, res);
};
const uniqueCache = async()=>{//delete duplicated caches on activate event
const cachedNames = await caches.keys();
cachedNames.forEach(cached=>cached == cacheName ? cached : caches.delete(cached));
};
const fetchCache = async(req) => {
console.log(req);
console.log('fetching');
const resp = await caches.match(req); // First try to get the resource from the cache
if(resp) return resp;
const res = await fetch(req); // Next try to get the resource from the network
if(res){
putNewCache(req, res.clone());
return res;
}
const fallback = await caches.match('/');
if(fallback) return fallback;
// if(!resp || !res || !fallback){
// return await caches.match('/');
// }
};
self.addEventListener("install",e=> e.waitUntil(addCache(cachedItems)));
// self.addEventListener("activate",e=>e.waitUntil(uniqueCache()));
self.addEventListener('activate',async(e)=>{
console.log({e,msg:"service worker activated"});
const cachedNames = await caches.keys();
cachedNames.forEach(cached=>cached == cacheName ? cached : caches.delete(cached));
});
self.addEventListener("fetch",e=>e.respondWith(fetchCache(e.request)));