-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
service-worker.js
59 lines (51 loc) · 1.65 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
self.addEventListener('install', function(event){
console.log('Install');
});
self.addEventListener('activate', function(event){
console.log('Activate');
});
var cacheName = 'railroutersg-v2';
caches.delete('railroutersg-v1'); // Delete the old one
var successResponses = /^0|([123]\d\d)|(40[14567])|410$/;
function fetchAndCache(request){
return fetch(request.clone()).then(function(response){
if (request.method == 'GET' && response && successResponses.test(response.status) && (response.type == 'basic' || /\.(js|png|ttf|woff|woff2)/i.test(request.url) || /fonts\.googleapis\.com/i.test(request.url))){
console.log('Cache', request.url);
caches.open(cacheName).then(function(cache){
cache.put(request, response);
});
}
return response.clone();
});
};
function cacheOnly(request){
return caches.open(cacheName).then(function(cache){
return cache.match(request);
});
};
// Fastest strategy from https://github.com/GoogleChrome/sw-toolbox
self.addEventListener('fetch', function(event){
var request = event.request;
var url = request.url;
event.respondWith(new Promise(function(resolve, reject){
var rejected = false;
var reasons = [];
var maybeReject = function(reason){
reasons.push(reason.toString());
if (rejected){
reject(new Error('Both cache and network failed: "' + reasons.join('", "') + '"'));
} else {
rejected = true;
}
};
var maybeResolve = function(result){
if (result instanceof Response){
resolve(result);
} else {
maybeReject('No result returned');
}
};
fetchAndCache(request.clone()).then(maybeResolve, maybeReject);
cacheOnly(request).then(maybeResolve, maybeReject);
}));
});