-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathservice-worker.js
87 lines (83 loc) · 2.47 KB
/
service-worker.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
'use strict'
var CACHE_NAME = 'dexpairs'
var FILES_TO_CACHE = [
'/',
'/index.html',
'/charts.html',
'/wallet.html',
'/news.html',
'/donate.html',
'/404.html',
'/feed.atom',
]
// Start the service worker and cache all of the app's shell content
self.addEventListener('install', async e => {
console.log('[ServiceWorker] Install')
e.waitUntil(
caches.open(CACHE_NAME).then(cache => {
return cache.addAll(FILES_TO_CACHE)
})
)
self.skipWaiting()
})
// Check if service worker is activated
self.addEventListener('activate', async e => {
// console.log('[ServiceWorker] Activate')
// Delete old static cache
e.waitUntil(
caches.keys().then(cacheNames => {
console.log(cacheNames)
return Promise.all(cacheNames
.filter(cacheName => cacheName !== CACHE_NAME)
.map(cacheName => caches.delete(cacheName))
)
})
)
self.clients.claim()
})
self.addEventListener('fetch', async event => {
if(event.request.method !== "GET" || event.request.url.includes('extension')) {
return
}
if (['font', 'image'].includes(event.request.destination)) {
// Cache first, falling back to network
// console.log('[ServiceWorker][CacheFirst] ', event.request.url)
event.respondWith(
caches.open(CACHE_NAME).then((cache) => {
return cache.match(event.request).then((cachedResponse) => {
return cachedResponse || fetch(event.request.url).then((fetchedResponse) => {
cache.put(event.request, fetchedResponse.clone())
return fetchedResponse
})
})
})
)
} else if (['document', 'script', 'style'].includes(event.request.destination) || event.request.url.includes('feed.atom')) {
// Stale-while-revalidate
// console.log('[ServiceWorker][StaleRevalidate] ', event.request.url)
event.respondWith(
caches.open(CACHE_NAME).then(async cache => {
return cache.match(event.request).then(async response => {
const fetchPromise = fetch(event.request).then(async networkResponse => {
cache.put(event.request, networkResponse.clone())
return networkResponse
})
return response || fetchPromise
})
})
)
} else {
// Network first, falling back to cache
// console.log('[ServiceWorker][NetworkFirst] ', event.request.url)
event.respondWith(
caches.open(CACHE_NAME).then(async cache => {
return fetch(event.request.url).then(async fetchedResponse => {
cache.put(event.request, fetchedResponse.clone())
return fetchedResponse
}).catch(() => {
return cache.match(event.request.url)
})
})
)
}
})