-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsw.js
More file actions
63 lines (59 loc) · 1.61 KB
/
sw.js
File metadata and controls
63 lines (59 loc) · 1.61 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
const CACHE_STATIC_NAME = 'static-v1';
const CACHE_DYNAMIC_NAME = 'dynamic'
const STATIC_FILES = [
'./',
'./index.html',
'./js/app.js',
'./css/style.css'
];
self.addEventListener('install', event => {
console.log('[Service Worker] Installing Service Worker ...');
event.waitUntil((async () => {
try {
const cache = await caches.open(CACHE_STATIC_NAME);
return cache.addAll(STATIC_FILES);
} catch(error) {
console.log(error);
}
})());
});
self.addEventListener('activate', event => {
console.log('[Service Worker] Activating Service Worker ....');
event.waitUntil((async () => {
try {
const keyList = await caches.keys();
keyList.forEach(async key => {
if (key !== CACHE_STATIC_NAME && key !== CACHE_DYNAMIC_NAME) {
console.log('[Service Worker] Removing old caches');
await caches.delete(key);
}
});
} catch(error) {
console.log(error);
}
})());
return self.clients.claim();
});
self.addEventListener('fetch', event => {
event.respondWith((async () => {
try {
let data = await caches.match(event.request);
if (data) {
return data;
} else {
try {
data = await fetch(event.request);
const cache = await caches.open(CACHE_DYNAMIC_NAME);
cache.put(event.request.url , data.clone());
return data;
} catch(error) {
const cache = await caches.open(CACHE_STATIC_NAME);
data = await cache.match('./offline.html');
return data;
}
}
} catch(error) {
console.log(error);
}
})());
});