blob: 0fa1e3e3625f7f4b980fe46ae767fc6504c60c67 (
plain)
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
|
//This is the service worker with the combined offline experience (Offline page + Offline copy of pages)
//Install stage sets up the offline page in the cache and opens a new cache
self.addEventListener('install', function(event) {
event.waitUntil(preLoad());
});
const cacheName = "cache-2019-11-01";
var preLoad = function(){
console.log('[PWA Builder] Install Event processing');
return caches.open(cacheName).then(function(cache) {
console.log('[PWA Builder] Cached index and offline page during Install');
return cache.addAll(['/blog/', '/blog', '/', '/contact', '/resume', '/talks', '/gallery']);
});
};
self.addEventListener('fetch', function(event) {
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') {
return;
}
console.log('[PWA Builder] The service worker is serving the asset.');
event.respondWith(checkResponse(event.request).catch(function() {
return returnFromCache(event.request);
}));
event.waitUntil(addToCache(event.request));
});
var checkResponse = function(request){
return new Promise(function(fulfill, reject) {
fetch(request).then(function(response){
if(response.status !== 404) {
fulfill(response);
} else {
reject();
}
}, reject);
});
};
var addToCache = function(request){
return caches.open(cacheName).then(function (cache) {
return fetch(request).then(function (response) {
console.log('[PWA Builder] add page to offline: ' + response.url);
return cache.put(request, response);
});
});
};
var returnFromCache = function(request){
return caches.open(cacheName).then(function (cache) {
return cache.match(request).then(function (matching) {
if(!matching || matching.status == 404) {
return cache.match('offline.html');
} else {
return matching;
}
});
});
};
|