forked from novchurch/songs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sw.js
81 lines (74 loc) · 2.8 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
---
---
const staticCacheName = 'static-cache-rigovanov-songs-v25';
const dynamicCacheName = 'dynamic-cache-rigovanov-songs-v25';
const staticAssets = [
'{{ "/" | relative_url }}',
'{{ "/alphabet/" | relative_url }}',
{% for post in site.posts -%}
'{{ post.url | relative_url }}',
{% endfor -%}
{% assign audio_files = site.static_files | where: "audio", true -%}
{% for myaudio in audio_files -%}
'{{ myaudio.path | relative_url }}',
{% endfor -%}
'{{ "/offline/" | relative_url }}',
{% if site.minimal -%}
'{{ "/assets/css/minimal.css" | relative_url }}',
'{{ "/assets/css/classes.css" | relative_url }}',
{% else -%}
'{{ "/assets/css/style.css" | relative_url }}',
{%- endif -%}
{% if site.sidebar -%}
'{{ "/assets/css/sidebar.css" | relative_url }}',
{%- endif %}
'{{ "/assets/fonts/PTSans-Regular.woff" | relative_url }}',
'{{ "/assets/fonts/PTSans-Bold.woff" | relative_url }}',
'{{ "/images/icons/hymnbook.svg" | relative_url }}',
'{{ "/images/icons/mask-hymnbook.svg" | relative_url }}',
'{{ "/assets/fontawesome/icons.svg" | relative_url }}',
'{{ "/favicon.ico" | relative_url }}',
'{{ "/js/app.js" | relative_url }}',
'{{ "/images/no-image.jpg" | relative_url }}',
'{{ "/manifest.json" | relative_url }}'
];
self.addEventListener('install', async event => {
const cache = await caches.open(staticCacheName);
console.log('Service worker now caching all content...');
await cache.addAll(staticAssets);
});
self.addEventListener('activate', async event => {
const cachesKeys = await caches.keys();
const checkKeys = cachesKeys.map(async key => {
if (![staticCacheName, dynamicCacheName].includes(key)) {
await caches.delete(key);
}
});
await Promise.all(checkKeys);
console.log('Service worker has been activated');
});
self.addEventListener('fetch', async event => {
console.log(`Trying to fetch ${event.request.url}`);
event.respondWith(checkCache(event.request));
});
async function checkCache(req) {
const cachedResponse = await caches.match(req);
return cachedResponse || checkOnline(req);
}
async function checkOnline(req) {
const cache = await caches.open(dynamicCacheName);
try {
const res = await fetch(req);
await cache.put(req, res.clone());
return res;
} catch (error) {
const cachedRes = await cache.match(req);
if (cachedRes) {
return cachedRes;
} else if (req.url.indexOf('.jpg') !== -1 || req.url.indexOf('.jpeg') !== -1 || req.url.indexOf('.png') !== -1 || req.url.indexOf('.svg') !== -1) {
return caches.match('{{ "/images/no-image.jpg" | relative_url }}');
} else {
return caches.match('{{ "/offline/" | relative_url }}');
}
}
}