-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
65 lines (56 loc) · 1.43 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
const staticAssets = [
'./',
'./bootstrap.min.css',
'./styles.css',
'./app.js',
'./favicon.ico',
'./offline.json',
'./offline.jpg'
]
const staticCacheName = 'just-news-static';
const dynamicCacheName = 'just-news-dynamic';
const newsApiCacheName = 'news-api-cache';
self.addEventListener('install', async e => {
const cache = await caches.open(staticCacheName);
cache.addAll(staticAssets);
});
self.addEventListener('activate', event => {
event.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', async e => {
const req = e.request;
const url = new URL(req.url);
if (url.origin === location.origin) {
e.respondWith(cacheFirst(req));
} else {
e.respondWith(networkFirst(req.clone()));
}
})
async function cacheFirst(req) {
const cache = await caches.open(staticCacheName);
const cachedResponse = await caches.match(req);
return cachedResponse || fetch(req);
}
async function networkFirst(req) {
let cache;
try {
let res = await fetch(req);
if (req.url.includes('mediastack')) {
cache = await caches.open(newsApiCacheName);
} else {
cache = await caches.open(dynamicCacheName);
}
cache.put(req, res.clone());
return res;
} catch (err) {
let res = await caches.match(req);
if (res) {
return res;
} else {
if (req.url.includes('news')) {
let res = await caches.match('./offline.json');
return res;
}
}
}
}