-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
93 lines (86 loc) · 1.89 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
82
83
84
85
86
87
88
89
90
91
92
93
const version = 1;
const preCacheName = `static-${version}`;
const precache = [
'/',
'/fonts/Poppins-Regular.woff',
'/index.html',
'/404.html',
'/img/bg.jpg',
'/img/profile.jpg',
];
//if you add '/404.html' to the precache, the file must exist or the install event will fail
self.addEventListener('install', (e) => {
//installed
e.waitUntil(
caches
.open(preCacheName)
.then((cache) => {
console.log('caching the static files');
cache.addAll(precache);
})
.catch(console.warn),
);
//load pre-cache
});
self.addEventListener('activate', (e) => {
//activating
e.waitUntil(
caches
.keys()
.then((keys) => {
return Promise.all(
keys
.filter((key) => key !== preCacheName)
.map((key) => caches.delete(key)),
);
})
.catch(console.warn),
);
//delete old caches
});
self.addEventListener('fetch', (e) => {
//fetch request received
//send back a response from cache or fetch
e.respondWith(
caches.match(e.request).then((cacheRes) => {
return (
cacheRes ||
fetch(e.request).then(
(response) => {
return response;
},
(err) => {
// added by me
console.log(
'[Service Worker] Fetch failed; returning offline page instead.',
err,
);
return precache;
//in case of network failure, send precache
},
)
);
}),
);
});
self.addEventListener('message', (e) => {
//message received
//do things based on message props
let data = e.data;
console.log('SW received', data);
});
const sendMessage = async (msg) => {
let allClients = await clients.matchAll({ includeUncontrolled: true });
return Promise.all(
allClients.map((client) => {
let channel = new MessageChannel();
return client.postMessage(msg);
}),
);
};
// PERIODIC SYNC
self.addEventListener('periodicsync', (e) => {
if (e.tag == 'latest-update') {
e.waitUntil(fetchAndCacheLatestUpdate());
}
});