-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice-worker.js
92 lines (80 loc) · 2.84 KB
/
service-worker.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
/*=================================================================
Licence obtained at https://www.apache.org/licenses/LICENSE-2.0
in license file
==================================================================*/
'use strict';
//Add list of files to cache
const FILES_TO_CACHE = [
'./',
'./index.html',
'./js/index.js',
'./js/install.js',
'./css/index.css',
'./img/cloud.svg',
'https://fonts.googleapis.com/css2?family=Kite+One&family=Nunito&display=swap',
'./favicon-16x16.png',
'./favicon-32x32.png',
'./favicon.ico',
'./android-chrome-192x192.png',
'./android-chrome-512x512.png',
'./site.webmanifest'
]
const CACHE_NAME = 'pages-cache-v2';
const DATA_CACHE_NAME = 'data-cache-v2';
self.addEventListener('install', event => {
console.log('Service worker installing...');
//Add a call to skipWaiting here
self.skipWaiting();
//Precahe static resources
event.waitUntil(
caches.open(CACHE_NAME).then(cache => {
console.log('[ServiceWorker] Pre-caching offline page');
return cache.addAll(FILES_TO_CACHE);
})
);
});
self.addEventListener('activate', event => {
console.log('Service worker activating...');
self.clients.claim();
//Remove previous cached data from disk.
event.waitUntil(
caches.keys().then(keyList => {
return Promise.all(keyList.map(key => {
if (key !== CACHE_NAME && key !== DATA_CACHE_NAME) {
console.log('[ServiceWorker] Removing old cache', key);
return caches.delete(key);
}
}));
})
);
});
self.addEventListener('fetch', event => {
//console.log('Fetching', event);
//console.log('Fetching', event.request.url);
if (event.request.url.includes('https://api.openweathermap.org/data/2.5/')) {
console.log('[Service Worker] Fetch (data)', event.request.url);
event.respondWith(
caches.open(DATA_CACHE_NAME).then(cache => {
return fetch(event.request)
.then(response => {
// If the response was good, clone it and store it in the cache.
if (response.status === 200) {
cache.put(event.request.url, response.clone());
}
return response;
}).catch((err) => {
// Network request failed, try to get it from the cache.
return cache.match(event.request);
})
}));
return;
}
event.respondWith(
caches.open(CACHE_NAME).then(cache => {
return cache.match(event.request)
.then(response => {
return response || fetch(event.request);
});
})
);
});