-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
50 lines (47 loc) · 1.37 KB
/
Copy pathsw.js
File metadata and controls
50 lines (47 loc) · 1.37 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
42
43
44
45
46
47
48
49
50
// Bump the version number to force phones to clear their old cache
const CACHE_NAME = 'rubbersoul-v3';
const ASSETS_TO_CACHE = [
'./',
'./index.html',
'./manifest.json',
'./icon-192.png',
'./icon-512.png'
];
// Install the service worker and cache the files
self.addEventListener('install', (event) => {
self.skipWaiting(); // Force the waiting service worker to become the active service worker
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll(ASSETS_TO_CACHE);
})
);
});
// Clean up old caches when the new version takes over
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cache) => {
if (cache !== CACHE_NAME) {
return caches.delete(cache);
}
})
);
})
);
});
// Network-First Strategy
self.addEventListener('fetch', (event) => {
event.respondWith(
fetch(event.request).then((response) => {
// If the network is good, save a fresh copy to the cache and return the response
return caches.open(CACHE_NAME).then((cache) => {
cache.put(event.request, response.clone());
return response;
});
}).catch(() => {
// If the network fails (offline), fall back to the cache
return caches.match(event.request);
})
);
});