-
Notifications
You must be signed in to change notification settings - Fork 2
/
sw.js
73 lines (60 loc) · 2.04 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
//Stale-while-revalidate strategy
// Fill here with your cache name-version.
const CACHE_NAME = 'deepfractal-0.0.1'
// This is the list of URLs to be cached by your Progressive Web App URLs.
const CACHED_URLS = [
'/',
'/index.html',
'/manifest.json',
'/src/old-src/events.js',
'/src/old-src/render.js',
'/src/old-src/shaders.js',
'/public/images/icons/android-chrome-192x192.png',
'/public/images/icons/android-chrome-512x512.png',
'/public/images/doge.jpg',
'/public/images/loli.jpg',
'/public/images/rick.jpg',
]
let cache = null
// Open cache on install.
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(currentCache => {
// Store a reference to current cache, to be used on fetch event handler.
cache = currentCache
cache.addAll(CACHED_URLS)
})
.then(self.skipWaiting())
)
})
// Handle fetch event with snippet stolen from here: https://www.youtube.com/watch?v=TtXvE814SQA
self.addEventListener('fetch', event => {
const request = event.request
const networkResponsePromise = fetch(request).catch(ignore => {})
const cachedResponsePromise = caches.match(request)
event.respondWith(async function () {
const cacheResponse = await cachedResponsePromise
if (cacheResponse) return cacheResponse
const networkResponse = await networkResponsePromise
if (networkResponse) return networkResponse.clone()
throw new Error(`Neither network nor cache had a response for ${request.url}`)
}())
event.waitUntil(async function () {
const networkResponse = await networkResponsePromise
if (networkResponse) cache.put(request, networkResponse.clone())
}())
})
// Clean up caches other than current.
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.filter(cacheName => {
const deleteThisCache = cacheName !== CACHE_NAME
return deleteThisCache
}).map(cacheName => caches.delete(cacheName))
)
})
)
})