/
service-worker.js
94 lines (84 loc) · 2.74 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
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
92
93
94
const CACHE_VERSION = 2;
let CURRENT_CACHES = {
offline: 'offline-v' + CACHE_VERSION,
assets: 'assets-v' + CACHE_VERSION
};
const OFFLINE_URL = 'index.html';
function createCacheBustedRequest(url) {
let request = new Request(url, {
cache: 'reload'
});
if ('cache' in request) {
return request;
}
// If {cache: 'reload'} didn't have any effect, append a cache-busting URL parameter instead.
let bustedUrl = new URL(url, self.location.href);
bustedUrl.search += (bustedUrl.search ? '&' : '') + 'cachebust=' + Date.now();
return new Request(bustedUrl);
}
self.addEventListener('install', event => {
event.waitUntil(
fetch(createCacheBustedRequest(OFFLINE_URL)).then(function (response) {
return caches.open(CURRENT_CACHES.offline).then(function (cache) {
return cache.put(OFFLINE_URL, response);
});
})
);
event.waitUntil(
caches.open(CURRENT_CACHES.assets).then(function (cache) {
return cache.addAll(
[
"/",
"/js/main.js",
"/css/main.css"
]
);
})
)
});
self.addEventListener('activate', event => {
let expectedCacheNames = Object.keys(CURRENT_CACHES).map(function (key) {
return CURRENT_CACHES[key];
});
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (expectedCacheNames.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
);
})
);
});
self.addEventListener('fetch', event => {
event.respondWith(
caches.open('dynamic-cache').then(function(cache) {
return cache.match(event.request).then(function (response) {
return response || fetch(event.request).then(function(response) {
cache.put(event.request, response.clone());
return response;
});
});
})
);
if (event.request.mode === 'navigate' ||
(event.request.method === 'GET' &&
event.request.headers.get('accept').includes('text/html'))) {
event.respondWith(
fetch(event.request).catch(error => {
return caches.match(OFFLINE_URL);
})
);
}
});
self.addEventListener('fetch', function (event) {
if (!event.request.headers.get('accept').includes('text/html')) {
event.respondWith(
caches.match(event.request).then(function (response) {
return response || fetch(event.request);
})
);
}
});