-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsw.js
64 lines (56 loc) · 1.86 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
'use strict';
const version = 'v1.03';
const staticCachePrefix = 'miband3-pd1-static-';
const staticCacheName = staticCachePrefix + version;
self.addEventListener('install', event => {
event.waitUntil(
caches.open(staticCacheName).then(cache => {
// cache all the static assets required for offline use.
return cache.addAll([
'./',
'index.html',
'webapp.bundle.js'
]);
}).then(() => {
// activate the new service worker immediately, without waiting for next load.
return self.skipWaiting();
})
);
});
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(cacheNames => {
// remove any old caches once the new service worker is activated.
return Promise.all(
cacheNames.filter(cacheName => {
return cacheName.startsWith(staticCachePrefix) && cacheName !== staticCacheName;
}).map(cacheName => {
return caches.delete(cacheName);
})
);
}).then(() => {
// tell service worker to take control of any open pages.
self.clients.claim();
})
);
});
self.addEventListener('fetch', event => {
let request = event.request;
let url = new URL(request.url);
// only deal with requests on the same domain.
if (url.origin !== location.origin) {
return;
}
// for non-GET requests, go to the network.
if (request.method !== 'GET') {
event.respondWith(fetch(request));
return;
}
// for everything else look to the cahce first,
// then fall back to the network.
event.respondWith(
caches.match(request).then(response => {
return response || fetch(request);
})
);
});