-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserviceWorker.js
More file actions
78 lines (69 loc) · 2.07 KB
/
serviceWorker.js
File metadata and controls
78 lines (69 loc) · 2.07 KB
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
const cacheName = 'cache-v1'
const filesToCache = [
'/index.html',
'/',
'/dist/assets/index.ff80710c.js',
'/dist/assets/index.07b5d4d5.css',
'/manifest.json',
'/tick-box-192x192.png',
'/tick-box-512x512.png',
'/icons8-tick-box.svg',
]
// Adding 'install' event listener
self.addEventListener('install', (event) => {
console.log('Event: Install')
event.waitUntil(
// Open the cache
caches
.open(cacheName)
.then((cache) => {
// Adding the files to cache
return cache.addAll(filesToCache).then(() => {
console.log('All files are cached.')
return self.skipWaiting() // To forces the waiting service worker to become the active service worker
})
})
.catch((err) => {
console.log(err)
}),
)
})
// Adding 'activate' event listener
self.addEventListener('activate', (event) => {
console.log('Event: Activate')
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
// eslint-disable-next-line array-callback-return
cacheNames.map((cache) => {
if (cache !== cacheName) {
// cacheName = 'cache-v1'
return caches.delete(cache) // Deleting the cache
}
}),
)
}),
)
return self.clients.claim() // To activate this SW immediately without waiting.
})
// Adding 'fetch' event listener
self.addEventListener('fetch', (event) => {
const request = event.request
// Tell the browser to wait for network request and respond with below
event.respondWith(
// If request is already in cache, return it
caches.match(request).then((response) => {
if (response) {
return response
}
// else add the request to cache and return the response
return fetch(request).then((response) => {
const responseToCache = response.clone() // Cloning the response stream in order to add it to cache
caches.open(cacheName).then((cache) => {
cache.put(request, responseToCache) // Adding to cache
})
return response
})
}),
)
})