This repository has been archived by the owner on Mar 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw.js
90 lines (81 loc) · 2.23 KB
/
sw.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
const cacheName = 'JE-Cache';
const startPage = 'https://justeat.jensz12.com';
const offlinePage = 'https://justeat.jensz12.com/';
const CACHING_DURATION = 7 * 24 * 3600;
const filesToCache = [
'/img/logo/192.png',
'/img/logo/512.png',
'/img/logo/1024.png',
'/img/logo/je.png',
];
// Install
self.addEventListener('install', function (e) {
console.log('Juest Eat service worker installation');
e.waitUntil(
caches.open(cacheName).then(function (cache) {
console.log('Just Eat service worker caching dependencies');
filesToCache.map(function (url) {
return cache.add(url).catch(function (reason) {
return console.log('Just Eat: ' + String(reason) + ' ' + url);
});
});
})
);
});
// Activate
self.addEventListener('activate', function (e) {
console.log('Just Eat service worker activation');
e.waitUntil(
caches.keys().then(function (keyList) {
return Promise.all(keyList.map(function (key) {
if (key !== cacheName) {
console.log('Just Eat old cache removed', key);
return caches.delete(key);
}
}));
})
);
return self.clients.claim();
});
// Fetch
self.addEventListener('fetch', function (e) {
// Return if request url protocal isn't http or https
if (!e.request.url.match(/^(http|https):\/\//i))
return;
// Return if request url is from an external domain.
if (new URL(e.request.url).origin !== location.origin)
return;
// For POST requests, do not use the cache. Serve offline page if offline.
if (e.request.method !== 'GET') {
e.respondWith(
fetch(e.request).catch(function () {
return caches.match(offlinePage);
})
);
return;
}
// Revving strategy
if (e.request.mode === 'navigate' && navigator.onLine) {
e.respondWith(
fetch(e.request).then(function (response) {
return caches.open(cacheName).then(function (cache) {
cache.put(e.request, response.clone());
return response;
});
})
);
return;
}
e.respondWith(
caches.match(e.request).then(function (response) {
return response || fetch(e.request).then(function (response) {
return caches.open(cacheName).then(function (cache) {
cache.put(e.request, response.clone());
return response;
});
});
}).catch(function () {
return caches.match(offlinePage);
})
);
});