forked from udacity/mws-restaurant-stage-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
52 lines (48 loc) · 1.35 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
var staticCacheName = 'restaurant-cache-v3';
/* Store assets in cache */
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(staticCacheName).then((cache) => {
return cache.addAll([
'/',
'/css/styles.css',
'/data/restaurants.json',
'/js/main.js',
'/js/restaurant_info.js',
'/js/dbhelper.js',
'/img/',
'/img270/'
]).then(() => self.skipWaiting());
})
);
});
/* Check for old cache and remove */
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.filter((cacheName) => {
return cacheName.startsWith('restaurant-cache-') &&
cacheName != staticCacheName;
}).map((cacheName) => {
return caches.delete(cacheName);
})
);
})
);
});
/* Fetch from network and store in cache */
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((resp) => {
return resp || fetch(event.request).then((response) => {
return caches.open(staticCacheName).then((cache) => {
cache.put(event.request, response.clone());
return response;
})
});
}).catch(() => {
console.log('Problem with network. Try again.');
})
);
});