-
Notifications
You must be signed in to change notification settings - Fork 0
/
serviceWorker.js
38 lines (33 loc) · 967 Bytes
/
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
const staticAssets = [
'/index.html',
'/css/main.css',
'/js/app.js'
];
self.addEventListener('install', async event => {
const cache = await caches.open('static-alismed');
cache.addAll(staticAssets);
});
self.addEventListener('fetch', event => {
//caching for offline viewing
const {request} = event;
const url = new URL(request.url);
if(url.origin === location.origin) {
event.respondWith(cacheData(request));
} else {
event.respondWith(networkFirst(request));
}
});
async function cacheData(request) {
const cachedResponse = await caches.match(request);
return cachedResponse || fetch(request);
}
async function networkFirst(request) {
const cache = await caches.open('dynamic-alismed');
try {
const response = await fetch(request);
cache.put(request, response.clone());
return response;
} catch (error){
return await cache.match(request);
}
}