-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw-cache-site.js
48 lines (45 loc) · 1.34 KB
/
sw-cache-site.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
const cacheName = 'v2';
// SW installation
// Cache the fetched files
self.addEventListener('install', (event) => {
console.log('Service Worker: installed');
});
// SW activation
// Clear previous cached assets
self.addEventListener('activate', (event) => {
console.log('Service Worker: activated');
// Remove previously cached assets
event.waitUntil(
caches.keys().then((cacheNamesInBrowser) => {
return Promise.all(
cacheNamesInBrowser.map((cacheNameInBrowser) => {
if (cacheName !== cacheNameInBrowser) {
console.log('Service Worker: clearing previous cache');
return caches.delete(cacheNameInBrowser);
}
})
);
})
);
});
// SW fetching
// When fetching assets, before connecting to the backend, look into the cache
self.addEventListener('fetch', (event) => {
console.log('Service Worker: fetching');
event.respondWith(
fetch(event.request)
.then((response) => {
// Make a copy of the response
const responseClone = response.clone();
// Open cache
caches.open(cacheName).then((cache) => {
// Add the response to the cache
cache.put(event.request, responseClone);
});
return response;
})
.catch((error) =>
caches.match(event.request).then((response) => response)
)
);
});