-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathservice-worker.js
68 lines (63 loc) · 1.78 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
const dataCachedName = 'GameData'
const cachedName = 'GameContents'
const filesToCache = [
'/',
'/index.html',
'/dist/bundle.js',
'/dist/bundle.js.map',
'/dist/vendor.bundle.js',
'/dist/vendor.bundle.js.map',
'/assets/css/style.css',
'/assets/images/bg.png',
'/assets/images/cactus01.png',
'/assets/images/cactus02.png',
'/assets/images/cactus03.png',
'/assets/images/cloud01.png',
'/assets/images/cloud02.png',
'/assets/images/cloud03.png',
'/assets/images/dino.png',
'/assets/images/dino_52x58.png',
'/assets/images/ground.png',
'/assets/images/loader-bar.png',
'/assets/images/loader-bg.png',
'/assets/images/mushroom2.png',
'/assets/images/obstacle.png',
'/assets/images/phaser-es6-webpack.png',
'/assets/images/playAgainButton.png',
'/assets/sfx/jump.wav',
'/assets/sfx/hit.wav',
'/assets/sprites/dino_52x58.png',
'/assets/sprites/player_sheet.png'
]
self.addEventListener('install', e => {
console.log('[ServiceWorker] Installed')
e.waitUntil(preCache())
})
self.addEventListener('fetch', e => {
console.log('[ServiceWorker] Serving the asset.')
e.respondWith(fromNetwork(e.request, 1000).catch(() => {
return fromCache(e.request)
}))
})
const preCache = () => {
caches.open(cachedName).then((cache) => {
console.log('[ServiceWorker] Caching app shell')
return cache.addAll(filesToCache)
})
}
const fromNetwork = (req, timeout) => {
return new Promise((resolve, reject) => {
let timeoutId = setTimeout(reject, timeout)
fetch(req).then((res) => {
clearTimeout(timeoutId)
resolve(res)
}, reject)
})
}
const fromCache = (req) => {
return caches.open(cachedName).then(cache => {
return cache.match(req).then(matching => {
return matching || Promise.reject(new Error('no-match'))
})
})
}