-
Notifications
You must be signed in to change notification settings - Fork 1
/
service-worker.js
113 lines (94 loc) · 2.31 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
// ** cache name **
const cacheName = 'tech-in-rio-assets-v1';
// ** utility static data **
const offlineResponse = new Response('You are offline', {
status: 200,
statusText: 'OK',
headers: new Headers({
'Content-Type': 'text/html',
}),
});
const assetsExtensions = [
'.css',
'.js',
'.png',
'.jpg',
'.jpeg',
'.gif',
'.svg',
'.ico',
'.json',
'.woff2',
'.woff',
'.ttf',
'.otf',
'.eot',
];
// ** install event and first cached resources **
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(cacheName).then((cache) => {
return cache.addAll([
// resources to be cached during installation
'/',
'/index.html',
'/manifest.json',
'/assets/css/main.css',
'/assets/js/main.js'
]);
})
);
});
// ** utility basic functions **
const cacheRequest = async (request, response) => {
const cache = await caches.open(cacheName);
cache.put(request, response.clone());
};
const shouldCacheRequest = (request) => {
if (request.method === 'GET') return true;
if (assetsExtensions.some((ext) => request.url.endsWith(ext))) return true;
return false;
};
const responseFromCache = async (url) => {
const cache = await caches.open(cacheName);
const cachedResponse = await cache.match(url);
if (!cachedResponse) {
return;
}
return cachedResponse;
};
const responseFromNetwork = async (request) => {
try {
const networkResponse = await fetch(request);
return networkResponse;
} catch (error) {
return;
}
};
const networkOnly = async (event) => {
event.respondWith(await responseFromNetwork(event.request));
};
const cacheFirstFallingBackToNetwork = async (event) => {
event.respondWith(
(async () => {
const cachedResponse = await responseFromCache(event.request.url);
if (cachedResponse) {
return cachedResponse;
}
try {
const networkResponse = await responseFromNetwork(event.request);
await cacheRequest(event.request, networkResponse);
return networkResponse;
} catch (error) {
return offlineResponse;
}
})()
);
};
self.addEventListener('fetch', async (event) => {
if (shouldCacheRequest(event.request)) {
cacheFirstFallingBackToNetwork(event);
} else {
return networkOnly(event);
}
});