-
Notifications
You must be signed in to change notification settings - Fork 10
/
serviceWorker.js
91 lines (84 loc) · 2.8 KB
/
serviceWorker.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
88
89
90
91
const version = 'v1_13';
const cacheKey = 'game-cache-' + version;
importScripts('./preloadAssetsList.js?' + version);
const DEFAULT_RESOURCES = [
'./',
'./index.html',
'./dist/vendor.js',
'./dist/bundle.js',
'./dist/bundle.css'
];
const EXCLUDE_RESOURCES = [
'./src/serviceWorkerInstaller.js',
'./serviceWorker.js',
'./preloadAssetsList.js'
];
RESOURCES = DEFAULT_RESOURCES.concat(
RESOURCES.map(([assetPath]) => './' + assetPath)
);
self.addEventListener('install', event => {
event.waitUntil(
caches.open(cacheKey)
.then(cache => cache.addAll(RESOURCES))
// .then(() => { console.log('INSTALL COMPLETE') })
);
});
self.addEventListener('fetch', event => {
// console.log('FETCH ' + event.request.url);
if (
EXCLUDE_RESOURCES.some(resource => {
resource = resource.replace(/^\.\//, '');
return event.request.url.includes(resource);
})
) {
// console.log('NOT A RESOURCE, LET BROWSER FETCH IT');
return;
}
event.respondWith(
fetch(event.request)
.then(response => {
if (!response.ok) {
// console.log('CONTENT UNAVAILABLE ' + event.request.url);
throw 'Content unavailable';
}
const responseCopy = response.clone();
caches.open(cacheKey)
.then(cache => {
// console.log('RECACHE ' + event.request.url);
cache.put(event.request, responseCopy);
});
return response;
})
.catch(() => caches.match(event.request)
.then(cached => {
if (!cached) {
throw 'Service Unavailable';
}
// console.log('TAKE FROM CACHE ' + cached.url);
return cached;
})
.catch(error => {
console.error('Read from cache failed: ' + error);
return new Response('<h1>Service Unavailable</h1>', {
status: 503,
statusText: 'Service Unavailable',
headers: new Headers({
'Content-Type': 'text/html'
})
});
})
)
);
});
self.addEventListener('activate', event => {
// console.log('ACTIVATE');
event.waitUntil(
caches.keys()
.then(keys => Promise.all(
keys
.filter(key => !key.endsWith(version))
// .map(key => { console.log('DELETE CACHE' + key);return key; })
.map(key => caches.delete(key))
))
);
});