-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserviceWorker.js
More file actions
41 lines (36 loc) · 1 KB
/
serviceWorker.js
File metadata and controls
41 lines (36 loc) · 1 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
/**
* A serviceWorker file is entirely event-driven.
* This means that it won’t run any code unless it’s responding to an event.
*
*/
// Any change in this file will trigger a new install event.
self.addEventListener('install', async event => {
console.log('install event', event);
await cacheAssets();
});
self.addEventListener('fetch', async event => {
console.log('fetch event', event);
const req = event.request;
event.respondWith(cacheFirst(req));
});
const cacheKey = 'test-pwa';
const staticAssets = [
// Cacheable assets list. All the paths should be valid.
'./',
'./index.html',
'./app.js',
'./styles.css',
];
async function cacheAssets() {
try {
const cache = await caches.open(cacheKey);
await cache.addAll(staticAssets);
} catch (error) {
console.warn('Error while caching assets: ', error);
}
}
async function cacheFirst(req) {
const cache = await caches.open(cacheKey);
const cachedResponse = await cache.match(req);
return cachedResponse || fetch(req);
}