-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsw.js
79 lines (72 loc) · 2.36 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
const CACHE_NAME = 'cache-assets-v1';
const songs = [
'believer', 'goodbyes', 'clouds', 'graveyard', 'blindinglights', 'whativedone'
]
const CACHED_ASSETS = ['/', '/index.html', '/assets/Songs.json',
'/assets/backgrounds/visualize.webm',
'https://fonts.gstatic.com/s/bebasneue/v14/JTUSjIg69CK48gW7PXoo9Wlhyw.woff2',
'https://fonts.gstatic.com/s/barlowcondensed/v12/HTxwL3I-JCGChYJ8VI-L6OO_au7B47rxz3bWuQ.woff2',
'https://fonts.gstatic.com/s/barlowcondensed/v12/HTx3L3I-JCGChYJ8VI-L6OO_au7B6xHT2g.woff2'];
self.addEventListener("install", (e) => {
e.waitUntil(
caches
.open(CACHE_NAME)
.then((cache) => {
songs.forEach(song => {
CACHED_ASSETS.push(`/assets/covers/${song}.webp`);
CACHED_ASSETS.push(`/assets/backgrounds/${song}.webm`);
})
cache.addAll(CACHED_ASSETS);
})
.then(() => self.skipWaiting())
);
});
self.addEventListener('activate', (e) => {
e.waitUntil(
caches.keys().then((keys) => {
return Promise.all(
keys.filter((key) => key != CACHE_NAME).map((nm) => caches.delete(nm))
);
})
);
});
self.addEventListener('fetch', e => {
const url = new URL(e.request.url);
const isOnline = self.navigator.onLine;
const isWEBP = url.href.endsWith('.webp');
const isWEBM = url.href.endsWith('.webm');
const isCSS = url.href.endsWith('.css');
const isJS = url.href.endsWith('.js') && !url.href.includes('chrome-extension');
const isFont = url.href.endsWith('woff2');
const isHTML = e.request.mode === 'navigate' || url.href.endsWith('.html');
const isJSON = url.href.endsWith('.json');
if(isOnline) {
e.respondWith(
isWEBM || isWEBP || isFont || isJSON ? cacheFirst(e) : isHTML || isCSS || isJS ? networkRevalidateAndCache(e) : fetch(e.request)
)
} else {
e.respondWith(cacheOnly(e))
}
});
function cacheFirst(e) {
return caches.match(e.request).then((cacheResponse) => {
return cacheResponse || fetch(e.request);
});
}
function cacheOnly(e) {
return caches.match(e.request);
}
function networkRevalidateAndCache(e) {
return fetch(e.request).then(
(fetchResponse) => {
if (fetchResponse.ok) {
return caches.open(CACHE_NAME).then((cache) => {
cache.put(e.request, fetchResponse.clone());
return fetchResponse;
});
} else {
return caches.match(e.request);
}
}
);
}