-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpwa-sw.js
50 lines (46 loc) · 1.77 KB
/
pwa-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
const version = '1.0.0';
const cacheName = 'cache-name';
const assets = [
// Add your assets here
];
// Cache all the files to make a PWA
self.addEventListener('install', installEvent => {
installEvent.waitUntil(
caches.open(cacheName).then(cache => {
return Promise.all(
assets.map(async url => {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch "${url}", status: ${response.status}`);
}
return await cache.put(url, response);
} catch (error) {
return console.error(`Failed to cache "${url}": ${error.message}`);
}
})
);
}).catch(error => console.error('Cache open failed:', error))
);
});
// Implement network-first strategy
self.addEventListener("fetch", fetchEvent => {
fetchEvent.respondWith(
fetch(fetchEvent.request).then(networkResponse => {
// If we got a response from the network, update the cache
if (networkResponse && networkResponse.status === 200) {
const responseClone = networkResponse.clone();
caches.open(cacheName).then(cache => {
try {
cache.put(fetchEvent.request, responseClone);
} catch (error) { }
});
}
return networkResponse;
}).catch(async () => {
// If the network is unavailable, use the cache
const cacheResponse = await caches.match(fetchEvent.request);
return cacheResponse || caches.match('/error/404');
})
);
});