-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice-worker.js
50 lines (47 loc) · 1.41 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
// Files to cache
const cacheName = 'test-v1';
const appShellFiles = [
'/',
'/index.html',
'/main.js',
'/styles/style.css',
'/icons/icon-128.png',
'/icons/icon-256.png',
'/icons/icon-512.png',
'/data/f1-drivers.json',
];
const driversImages = [];
for (let i = 1; i <= 10; i++) {
driversImages.push(`/data/images/${i}.jpeg`);
}
const contentToCache = appShellFiles.concat(driversImages);
// Installing Service Worker
self.addEventListener('install', (e) => {
console.log('[Service Worker] Install');
e.waitUntil(
(async () => {
const cache = await caches.open(cacheName);
console.log('[Service Worker] Caching all: app shell and content');
await cache.addAll(contentToCache);
})()
);
});
// Fetching content using Service Worker
self.addEventListener('fetch', (e) => {
// Cache http and https only, skip unsupported chrome-extension:// and file://...
if (!(e.request.url.startsWith('http:') || e.request.url.startsWith('https:'))) {
return;
}
e.respondWith(
(async () => {
const r = await caches.match(e.request);
console.log(`[Service Worker] Fetching resource: ${e.request.url}`);
if (r) return r;
const response = await fetch(e.request);
const cache = await caches.open(cacheName);
console.log(`[Service Worker] Caching new resource: ${e.request.url}`);
cache.put(e.request, response.clone());
return response;
})()
);
});