-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw-cache-pages.js
56 lines (51 loc) · 1.31 KB
/
sw-cache-pages.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
const cacheName = 'v1';
const cacheAssets = [
'index.html',
'about.html',
'/css/style.css',
'/js/main.js',
];
// SW installation
// Cache the fetched files
self.addEventListener('install', (event) => {
console.log('Service Worker: installed');
event.waitUntil(
caches
.open(cacheName)
.then((cache) => {
console.log('Service Worker: caching files');
cache.addAll(cacheAssets);
})
.then(() => {
self.skipWaiting();
})
);
});
// 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, if the fetch failed (maybe offline), look into the cache
self.addEventListener('fetch', (event) => {
console.log('Service Worker: fetching');
event.respondWith(
fetch(event.request).catch(() => {
caches.match(event.request);
})
);
});