-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw.js
93 lines (73 loc) · 2.15 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
if (navigator && navigator.serviceWorker) {
navigator.serviceWorker.register('sw.js');
}
// Core assets
let coreAssets = ['index.html'];
// On install, cache core assets
self.addEventListener('install', function (event) {
// Cache core assets
event.waitUntil(caches.open('app').then(function (cache) {
for (let asset of coreAssets) {
cache.add(new Request(asset));
}
return cache;
}));
});
// Listen for request events
self.addEventListener('fetch', function (event) {
// Get the request
let request = event.request;
// Bug fix
// https://stackoverflow.com/a/49719964
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') return;
// HTML files
// Network-first
if (request.headers.get('Accept').includes('text/html')) {
event.respondWith(
fetch(request).then(function (response) {
// Create a copy of the response and save it to the cache
let copy = response.clone();
event.waitUntil(caches.open('app').then(function (cache) {
return cache.put(request, copy);
}));
// Return the response
return response;
}).catch(function (error) {
// If there's no item in cache, respond with a fallback
return caches.match(request).then(function (response) {
return response || caches.match('/offline.html');
});
})
);
}
// CSS & JavaScript
// Offline-first
if (request.headers.get('Accept').includes('text/css') || request.headers.get('Accept').includes('text/javascript')) {
event.respondWith(
caches.match(request).then(function (response) {
return response || fetch(request).then(function (response) {
// Return the response
return response;
});
})
);
return;
}
// Images
// Offline-first
if (request.headers.get('Accept').includes('image')) {
event.respondWith(
caches.match(request).then(function (response) {
return response || fetch(request).then(function (response) {
// Save a copy of it in cache
let copy = response.clone();
event.waitUntil(caches.open('app').then(function (cache) {
return cache.put(request, copy);
}));
// Return the response
return response;
});
})
);
}
});