-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw.js
50 lines (49 loc) · 1.52 KB
/
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 cacheVersion = 'v1';
if(self.constructor.name === "Window"){
window.addEventListener('load', () => {
navigator.serviceWorker
.register('sw.js')
.then(registration => {
console.log('Service Worker Registered');
})
.catch(error => {
console.log('Service Worker Registration Failed:', error);
});
});
}else if(self.constructor.name === "ServiceWorkerGlobalScope"){
self.addEventListener('activate', event => {
console.log('Service Worker: Activated');
// Remove old caches
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cache => {
if (cache !== cacheVersion) {
console.log('Service Worker: Clearing Old Cache');
return caches.delete(cache);
}
})
);
})
);
});
// Event listener for fetch requests
self.addEventListener('fetch', event => {
console.log('Service Worker: Fetching');
event.respondWith(
// Try to fetch the resource
fetch(event.request)
.then(response => {
// Clone the response
const responseClone = response.clone();
// Open cache and add the fetched resource
caches.open(cacheVersion).then(cache => {
cache.put(event.request, responseClone);
});
return response;
})
// If fetch fails, try to get from cache
.catch(() => caches.match(event.request).then(response => response))
);
});
}