-
Notifications
You must be signed in to change notification settings - Fork 0
/
service-worker.js
53 lines (47 loc) · 1.2 KB
/
service-worker.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
const staticAssets = [
'./',
'./script.js',
'./style.css',
'./index.html',
'./favourite.html',
'./favourite.js'
];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open('v1')
.then(res => {
console.log('wait.........!')
return res.addAll(staticAssets);
})
);
console.log('installed');
// var cache = caches.open('v1');
// cache.addAll(staticAssets);
});
self.addEventListener('activate', (event) => {
console.log('activated');
});
self.addEventListener('fetch', (ev) => {
console.log('Fetch from Service Worker ', ev);
const req = ev.request;
const url = new URL(req.url);
if (url.origin === location.origin) {
ev.respondWith(cacheFirst(req));
}
return ev.respondWith(networkFirst(req));
});
async function cacheFirst(req) {
let cacheRes = await caches.match(req);
return cacheRes || fetch(req);
}
async function networkFirst(req) {
const dynamicCache = await caches.open('v1-dynamic');
try {
const networkResponse = await fetch(req);
dynamicCache.put(req, networkResponse.clone());
return networkResponse;
} catch (err) {
const cacheResponse = await caches.match(req);
return cacheResponse;
}
}