-
-
Notifications
You must be signed in to change notification settings - Fork 133
/
service-worker.js
62 lines (54 loc) · 1.68 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
self.addEventListener('install', function(event){
console.log('Install');
});
self.addEventListener('activate', function(event){
console.log('Activate');
});
var cacheName = 'hackerweb-v1';
var successResponses = /^0|([123]\d\d)|(40[14567])|410$/;
function fetchAndCache(request){
console.log('fetchAndCache', request.url);
return fetch(request.clone()).then(function(response){
console.log(request.method, request.url, response.status, response.type);
if (request.method == 'GET' && response && successResponses.test(response.status) && response.type == 'basic'){
console.log('Cache', request.url);
caches.open(cacheName).then(function(cache){
cache.put(request, response);
});
}
return response.clone();
});
};
function cacheOnly(request){
console.log('cacheOnly', request.url);
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;
console.log('Fetch', 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);
}));
});