-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw.js
55 lines (48 loc) · 1.33 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
/* global self, caches, fetch, Response, Headers */
const cacheName = 'asteroids-cache-v1';
const urlsToCache = [
'',
'index.html',
'src/asteroids-apod.html',
'src/asteroids-app.html',
'src/asteroids-list.html',
'src/asteroids-detail.html',
'src/asteroids-route.html',
'src/asteroids-single.html'
];
self.addEventListener('install', event => {
// Perform install steps
event.waitUntil(
caches.open(cacheName)
.then(cache => cache.addAll(urlsToCache))
);
});
// Cache responses
self.addEventListener('fetch', event => {
event.respondWith(
caches
.match(event.request)
.then(cached => {
const networked = fetch(event.request)
.then(fetchedFromNetwork, unableToResolve)
.catch(unableToResolve);
return cached || networked;
function fetchedFromNetwork(response) {
const cacheCopy = response.clone();
caches
.open(cacheName)
.then(cache => cache.put(event.request, cacheCopy));
return response;
}
function unableToResolve() {
return new Response('<h1>Service Unavailable</h1>', {
status: 503,
statusText: 'Service Unavailable',
headers: new Headers({
'Content-Type': 'text/html'
})
});
}
})
);
});