forked from udacity/mws-restaurant-stage-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw.js
78 lines (74 loc) · 2.25 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
// Fetch, install, activate cache
const version = 'v6',
staticCacheName = 'reviews-cache-' + version,
filesToCache = [
'/',
'/index.html',
'/restaurant.html',
'/css/styles.css',
'/img/1.jpg',
'/img/2.jpg',
'/img/3.jpg',
'/img/4.jpg',
'/img/5.jpg',
'/img/6.jpg',
'/img/7.jpg',
'/img/8.jpg',
'/img/9.jpg',
'/img/10.jpg',
'/js/dbhelper.js',
'/js/idb.js',
'/js/register.js',
'/js/main.js',
'/js/restaurant_info.js'
];
// fetch cache, with fallbacks
addEventListener('fetch', fetchEvent => {
console.log("Fetching cache...", fetchEvent);
const request = fetchEvent.request;
fetchEvent.respondWith(
caches.match(request)
.then(response => {
if(response) return response;
return fetch(request)
.then(networkResponse => {
if(networkResponse === 404) return;
return caches.open(staticCacheName)
.then(cache => {
cache.put(request.url, networkResponse.clone());
return networkResponse;
})
})
.catch( error => {
console.log(error);
return;
}); // fetch catch
}) // end match
) // end respondWith
}); // end eventListener
// first install cache of application shell
addEventListener('install', installEvent => {
console.log("Installing service worker...", installEvent);
skipWaiting();
installEvent.waitUntil(
caches.open(staticCacheName)
.then(staticCache => staticCache.addAll(filesToCache))
) // end waitUntil
}); // end eventListener
// activate cache, remove outdated caches
addEventListener('activate', activateEvent => {
console.log("Activating service worker...", activateEvent);
activateEvent.waitUntil(
caches.keys()
.then(cacheNames => {
return Promise.all(
cacheNames.map(
cacheName => {
if(cacheName !== staticCacheName) return caches.delete(cacheName);
}
) // end map
) // end Promise.all
}) // end keys
.then(() => clients.claim()) // clear for open tabs
) // end waitUntil
}); // end eventListener