This repository has been archived by the owner on Nov 5, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pwa.js
48 lines (43 loc) · 1.72 KB
/
pwa.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_VERSION = 'lemonade-offline-v1'
self.addEventListener('install', function (event) {
var offlinePage = new Request('/offline.html')
event.waitUntil(
fetch(offlinePage).then(function (response) {
return caches.open(CACHE_VERSION).then(function (cache) {
console.log('[PWA Builder] Cached offline page during Install: ' + response.url)
return cache.put(offlinePage, response)
})
}))
})
//If any fetch fails, it will show the offline page.
//Maybe this should be limited to HTML documents?
self.addEventListener('fetch', function (event) {
if (event.request.url.indexOf('/ajax/') !== -1)
return
event.respondWith(
fetch(event.request).catch(function (error) {
console.error('[PWA Builder] Network request Failed. Serving offline page ' + error)
return caches.open(CACHE_VERSION).then(function (cache) {
return cache.match('offline.html')
})
}
))
})
//This is a event that can be fired from your page to tell the SW to update the offline page
self.addEventListener('refreshOffline', function (response) {
return caches.open(CACHE_VERSION).then(function (cache) {
console.log('[PWA Builder] Offline page updated from refreshOffline event: ' + response.url)
return cache.put(offlinePage, response)
})
})
self.addEventListener('activate', function (event) {
event.waitUntil(
caches.keys().then(function (keyList) {
return Promise.all(keyList.map(function (key) {
if (CACHE_VERSION !== key) {
return caches.delete(key)
}
}))
})
)
})