forked from lingonsaft/hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw.js
71 lines (67 loc) · 1.73 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const hacktoberCache = 'v1';
const cacheFiles = [
'./',
'./index.html',
'./contributors.html',
'./helpful-material.html',
'./css/contributors.css',
'./css/footer.css',
'./css/helpful-material.css',
'./css/index.css',
'./css/navbar.css',
];
// install the service worker
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(hacktoberCache).then((cache) => {
console.log('SW Cache is installing');
return cache.addAll(cacheFiles);
}).then((skip) => {
console.log('Service Worker Skip waiting');
self.skipWaiting();
console.log('Service Worker properly installed');
return skip;
}).catch((error) => {
console.log('SW Open & Cache install failed with ' + error);
})
);
});
// activate service worker
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((hacktoberCaches) => {
return Promise.all(hacktoberCaches.map((cache) => {
//if cache versions to not match, delete old version
if (cache !== hacktoberCache) {
return caches.delete(cache);
}
}));
})
);
});
// fetch service worker
self.addEventListener('fetch', (event) => {
let request = event.request;
event.respondWith (
fetch(request).then(
(response) => {
//check valid response basic means we do NOT cache 3rd party responses
if(!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
let responseToCache = response.clone();
caches.open(hacktoberCache)
.then((cache) => {
cache.put(request, responseToCache);
});
return response;
}
).catch((err) => {
caches.match(request).then((response) => {
if (response) {
return response;
}
})
})
);
});