-
Notifications
You must be signed in to change notification settings - Fork 0
/
serviceWorker.js
95 lines (87 loc) · 2.35 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
const cacheVersion = '1.0';
const cacheName = 'currencyConverter.io';
const cachNameVersion= `${cacheName}-${cacheVersion}`;
//*
const cachableAPI = [
'https://free.currencyconverterapi.com/api/v5/currencies',
'https://fonts.googleapis.com/css?family=Markazi+Text',
'https://fonts.googleapis.com/css?family=Galada'
];
const cachableFiles = [
'./',
'./img/AGNB-loading.gif',
'./img/51Tn1CC9wlL.png',
'./img/calculator-icon.png',
'./index.html',
'./css/alcproject.css',
'./js/emmsdanExtra.js',
'./js/controller.js',
'./js/converter.js',
'./js/database.js',
'./serviceWorker.js'
]
self.addEventListener('install', (event) => {
event.waitUntil(
//get cache first time
caches.open(cachNameVersion)
.then((cache) => {
try {
return cache.addAll(cachableFiles.concat(cachableAPI))
}catch (e) {
return 'Could not Access Server';
}
})
);
});
self.addEventListener('activate', (event) => {
event.waitUntil(
//activate new cache
caches.keys()
.then( (keys) => {
return Promise.all(keys.map((key, i) => {
if(key !== cachNameVersion){
return caches.delete(keys[i]);
}
}))
})
)
});
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('./');
})