-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache-worker.js
More file actions
62 lines (60 loc) · 1.48 KB
/
cache-worker.js
File metadata and controls
62 lines (60 loc) · 1.48 KB
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
var CACHE_NAME = 'static-cache-v7';
var urlsToCache = [
'.',
'index.html',
'styles/app.css',
'javascript/app.js',
'https://cdnjs.cloudflare.com/ajax/libs/open-iconic/1.1.1/font/css/open-iconic-bootstrap.min.css',
];
self.addEventListener('install', function(event) {
self.skipWaiting();
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
return response || fetchAndCache(event.request);
})
.catch(e => {
console.log('failed fetch', e)
return fetch(event.request)
})
);
});
function fetchAndCache(url) {
return fetch(url)
.then(function(response) {
// Check if we received a valid response
if (!response.ok) {
throw Error(response.statusText);
}
return caches.open(CACHE_NAME)
.then(function(cache) {
cache.put(url, response.clone());
return response;
});
})
.catch(function(error) {
console.log('Request failed:', error);
// try again...
return fetch(url)
});
}
self.addEventListener('activate', function(event) {
var cacheWhitelist = [CACHE_NAME];
event.waitUntil(
caches.keys().then(function(keyList) {
return Promise.all(keyList.map(function(key) {
if (cacheWhitelist.indexOf(key) === -1) {
return caches.delete(key);
}
}));
})
);
});