-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserviceworker.js
48 lines (42 loc) · 1000 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
39
40
41
42
43
44
45
46
47
48
const CACHE_NAME = 'version-1'
const urlsToCache = ['index.html']
const self=this
// install SW
self.addEventListener('install', (e)=>{
e.waitUntil(
(async() => {
try {
const cache_obj = await caches.open(CACHE_NAME)
cache_obj.addAll(urlsToCache)
console.log("cached urls")
}
catch{
console.log("error occured while caching...")
}
})()
)
})
// listen to requests
self.addEventListener('fetch', (e)=>{
e.respondWith(
caches.match(e.request)
.then(()=>{
return fetch(e.request)
.catch(()=>caches.match(urlsToCache[0]))
})
)
})
// Activate SW
self.addEventListener('activate', (e)=>{
const cacheWhiteList = []
cacheWhiteList.push(CACHE_NAME)
e.waitUntil(
caches.keys().then((cacheNames)=>Promise.all(
cacheNames.map((cacheName)=>{
if(!cacheWhiteList.includes(cacheName)){
return caches.delete(cacheName)
}
})
))
)
})