-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathservice-worker.js
77 lines (72 loc) · 1.99 KB
/
service-worker.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
/* eslint-disable */
const CACHE_NAME = 'js-cache';
/**
* Installing the service worker. Fetching the list of hashed resources from assets.json
* on event installation. That way our cache remains fresh.
*/
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME).then(cache => {
// Reading assets to be cached from assets.json file
return fetch('build/assets.json')
.then(response => {
return response.json();
})
.then(res => {
if (res) {
const resKeys = Object.keys(res).filter(Boolean);
return resKeys.map(keys => res[keys].js);
}
return [];
})
.then(filesToBeCached => {
return cache.addAll(filesToBeCached);
});
})
);
});
/**
* Handling fetch requests
*/
self.addEventListener('fetch', event => {
event.respondWith(
// Matching if requested resource is in cache
// If yes, then serve it otherwise make a network request.
caches.match(event.request, { ignoreSearch: true }).then(response => {
if (response) {
return response;
}
const fetchRequest = event.request.clone();
return fetch(fetchRequest).then(response => {
// Checking if its not a opaque response
if (!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
// Not found in cache, making network request
// Clone the response stream. Stream can be consumed once.
// Hence by cloning it, we send one copy back to browser
// and another copy to cache.
const responseClone = response.clone();
caches.open(CACHE_NAME).then(cache => {
// Storing the response of network request in cache
cache.put(event.request, responseClone);
});
return response;
});
})
);
});
/**
* Delete old caches when new service worker activates.
*/
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
return caches.delete(cacheName);
})
);
})
);
});