-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
81 lines (76 loc) · 1.87 KB
/
sw.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const cacheName = 'static';
const staticAssests = [
'./',
'./index.html',
'./main.css',
'./script.js',
'./icons/loader.gif',
'./icons/01d.png',
'./icons/01n.png',
'./icons/02d.png',
'./icons/02n.png',
'./icons/03d.png',
'./icons/03n.png',
'./icons/04d.png',
'./icons/04n.png',
'./icons/09d.png',
'./icons/09n.png',
'./icons/10d.png',
'./icons/10n.png',
'./icons/11d.png',
'./icons/11n.png',
'./icons/13d.png',
'./icons/13n.png',
'./icons/50d.png',
'./icons/50n.png',
'./icons/unknown.png',
'./icons/icon-144x144.png',
'./icons/icon-192x192.png',
'./icons/icon-512x512.png',
'./favicon-16x16.png',
'./favicon-32x32.png',
'./manifest.webmanifest'
]
self.addEventListener('install', async e => {
console.log('SW INSTALLED');
e.waitUntil(
await caches.open(cacheName)
.then(function(cache) {
cache.addAll(staticAssests);
})
)
return self.skipWaiting();
});
self.addEventListener('activate', e => {
console.log('SW ACTIVATED');
self.clients.claim();
});
self.addEventListener('fetch', async e => {
const req = e.request;
const url = new URL(req.url);
try {
if(url.origin === location.origin) {
e.respondWith(cacheFirst(req));
} else {
e.respondWith(networkAndCache(req));
}
} catch (e) {
return e;
}
})
async function cacheFirst(req) {
const cache = await caches.open(cacheName);
const cached = await cache.match(req);
return cached || fetch(cache)
}
async function networkAndCache(req) {
const cache = await caches.open(cacheName);
try {
const fresh = await fetch(req);
await cache.put(req, fresh.clone());
return fresh;
} catch (e) {
const cached = await cache.match(req);
return cached;
}
}