-
Notifications
You must be signed in to change notification settings - Fork 25
/
sw.js
85 lines (67 loc) · 1.95 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
'use strict';
console.log('Service worker startup');
const CACHE_NAME = 'webdrone-cache-1_2';
self.addEventListener('install', event => {
function onInstall () {
return caches.open(CACHE_NAME)
.then(cache => {
console.log('Caching required assets on installation');
cache.addAll(
[
'/',
'/index.html',
'/css/styles.css',
'/js/drone.v1.2.js',
'/js/main.v1.2.js'
]);
}
);
}
event.waitUntil(onInstall(event));
});
self.addEventListener('fetch', event => {
// If we can fetch latest version, then do so
let responsePromise = fetch(event.request)
.then(response => {
if (!response || response.status >= 300 || response.type !== 'basic') {
// Don't cache response if it's not within our domain or not 2xx status
return response;
}
let responseToCache = response.clone();
caches.open(CACHE_NAME)
.then(cache => {
cache.put(event.request, responseToCache);
console.log('Cached this response', responseToCache);
});
return response;
})
.catch(err => {
console.log('Fetch failed, maybe we are offline, try cache', err);
return caches.match(event.request)
.then(response => {
if (response) {
console.log('Cache hit', event.request);
return response;
} else {
console.warn('Offline cache miss');
}
}
);
});
event.respondWith(responsePromise);
});
// Clear out old versions
self.addEventListener('activate', function(event) {
var cacheWhitelist = [CACHE_NAME];
event.waitUntil(
caches.keys(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheWhitelist.indexOf(cacheName) == -1) {
return caches.delete(cacheName);
}
})
)
})
);
});