-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserviceworker.js
99 lines (90 loc) · 2.93 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
importScripts('./localforage.js')
const cacheName = 'v1';
const cacheAssets = [
'./index.html',
'./index.css',
'./main.js',
'./localforage.js'
]
// self.addEventListener('fetch', (e) => {
// e.respondWith(
// caches.match(e.request).then((r) => {
// //console.log('[Service Worker] Fetching resource: '+e.request.url);
// return r || fetch(e.request).then((response) => {
// return caches.open(cacheName).then((cache) => {
// console.log('[Service Worker] Caching new resource: '+e.request.url);
// cache.put(e.request, response.clone());
// return response;
// });
// });
// })
// );
// });
// Call Install Event
self.addEventListener('install', async (e) => {
console.log('Service Worker: Installed')
// Storing data into cache
const cache = await caches.open(cacheName)
cache.addAll(cacheAssets)
});
// Call Activate Event
self.addEventListener('activate', (e) => {
console.log('Service Worker: Activated')
// Remove unwanted caches
e.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cache => {
if(cache !== cacheName){
console.log('Service Worker: Clearing Old Cache')
return caches.delete(cache)
}
})
)
})
.catch(err => console.error(err))
)
});
// Call Fetch Event
self.addEventListener('fetch', async (e) => {
console.log('Service Worker: Fetching')
// CacheFirstThenNetwork
const req = e.request
const url = new URL(req.url)
if(url.origin === location.origin){
// Get data from cache
console.log('Cache first', cacheFirst(req))
e.respondWith(cacheFirst(req))
} else {
// Get data from network
console.log('Netwerk first')
e.respondWith(networkFirst(req))
}
});
const cacheFirst = async (req) => {
// const cacheResponse = await caches.match(req)
// return cacheResponse || fetch(req)
const cacheResponse = caches.match(req).then((r) => {
console.log('[Service Worker] Fetching resource: '+req.url);
return r || fetch(req).then((response) => {
return caches.open(cacheName).then((cache) => {
console.log('[Service Worker] Caching new resource: '+req.url);
cache.put(req, response.clone());
return response;
});
});
})
return cacheResponse
}
const networkFirst = async (req) => {
try {
const res = await fetch(req)
const data = await res.clone().json()
localforage.setItem('data', data)
return res
} catch (err) {
console.error('Fetching data failed: ' + err)
const storage = await localeforage.getItem('data')
return new Response(storage)
}
}