-
Notifications
You must be signed in to change notification settings - Fork 12
/
sw.js
74 lines (65 loc) · 2.31 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
66
67
68
69
70
71
72
73
74
// Choose a cache name
const cacheName = 'nextntp_v1.0.0'
// List the files to precache
const precacheResources = [
'./',
'./index.html',
'./nextntp.min.css',
'./nextntp.min.js',
'./nextntp.svg',
'./nextntpbg_d.svg',
'./nextntpbg.svg',
'./nextntpd.svg',
'./nextntpl.svg'
]
// When the service worker is installing, open the cache and add the precache resources to it
self.addEventListener('install', (event) => {
console.log('Service worker install event!')
event.waitUntil(
caches.open(cacheName).then((cache) => cache.addAll(precacheResources))
)
})
self.addEventListener('activate', function (event) {
var cacheAllowlist = ['nextntp_v1.0.0']
event.waitUntil(
caches.keys().then(function (cacheNames) {
return Promise.all(
cacheNames.map(function (cacheName) {
if (cacheAllowlist.indexOf(cacheName) === -1) {
return caches.delete(cacheName)
}
})
)
})
)
})
// When there's an incoming fetch request, try and respond with a precached resource, otherwise fall back to the network
self.addEventListener('fetch', (e) => {
console.log('Fetch intercepted for:', e.request.url)
e.respondWith(
(async function () {
const cachedResponse = await caches.match(e.request)
if (cachedResponse) {
return cachedResponse
}
const networkResponse = await fetch(e.request)
const hosts = [
'https://lh3.googleusercontent.com/proxy',
'https://logos.kiwibrowser.com'
]
if (hosts.some((host) => e.request.url.startsWith(host))) {
// This clone() happens before `return networkResponse`
const clonedResponse = networkResponse.clone()
e.waitUntil(
(async function () {
const cache = await caches.open(cacheName)
// This will be called after `return networkResponse`
// so make sure you already have the clone!
await cache.put(e.request, clonedResponse)
})()
)
}
return networkResponse
})()
)
})