-
Notifications
You must be signed in to change notification settings - Fork 0
/
serviceWorker.js
109 lines (100 loc) · 2.74 KB
/
serviceWorker.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*
* author @emmsdan
* for @alc 3.0
* date @2018-june
*/
const cacheVersion = '3.0';
const cacheName = 'currencyConverter.io';
const cachNameVersion= `${cacheName}-${cacheVersion}`;
/* add api files to be cached */
const cachableAPI = [
'https://free.currencyconverterapi.com/api/v5/currencies'
];
/* other files to be cached */
const cachableFiles = [
'./',
'./img/AGNB-loading.gif',
'./img/51Tn1CC9wlL.png',
'./index.html',
'./css/alcproject.css',
'./js/emmsdanExtra.js',
'./js/controller.js',
'./js/converter.js',
'./js/database.js',
'./serviceWorker.js',
'./icons/icon-72x72.png',
'./icons/icon-96x96.png',
'./icons/icon-128x128.png',
'./icons/icon-144x144.png',
'./icons/icon-152x152.png',
'./icons/icon-384x384.png',
'./icons/icon-384x384.png',
]
self.addEventListener('install', (event) => {
event.waitUntil(
//add cache to system
caches.open(cachNameVersion)
.then((cache) => {
try {
return cache.addAll(cachableFiles.concat(cachableAPI))
}catch (e) {
return 'Could not Access Server';
}
})
);
});
/* removes old cached files and update it to the latest version */
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys()
.then( (keys) => {
return Promise.all(keys.map((key, i) => {
if(key !== cachNameVersion){
return caches.delete(keys[i]);
}
}))
})
)
});
/*
handles all request made by the browser.
*/
self.addEventListener('fetch', (event) => {
let url = event.request.clone();
if (event.request.mode === 'navigate' || (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
event.respondWith(
fetch(event.request).catch(error => {
console.log('Oops, You are offline, Currently');
return caches.match('index.html');
})
);
}else{
event.respondWith(
caches.match(event.request)
.then((res) => {
if(res){
return res;
}
return fetch(url).then((res) => {
if(!res || res.status !== 200 || res.type !== 'basic'){
return res;
}
let response = res.clone();
caches.open(cachNameVersion)
.then((cache) => {
cache.put(event.request, response);
});
return res;
}).catch ((error)=> {
return error;
})
})
)
}
});
self.addEventListener('message', messageEvent => {
if (messageEvent.data === 'skipWaiting') return skipWaiting();
});
self.addEventListener('controllerchange', () => {
window.location.assign('./');
})