-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathsw.js
63 lines (56 loc) · 1.84 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
const CACHE_VER = 'v2';
const cacheInit = async () => {
caches.open(CACHE_VER).then(function (cache) {
return cache.addAll([
'./assets/css/shared/sp/css/common.css',
'./assets/css/main.css',
'./assets/js/umami.js',
'./assets/js/ufunction.js',
'./assets/js/mikuplayer.min.js',
'./assets/js/miku.js'
]);
});
};
const deleteCache = async (key) => {
await caches.delete(key);
};
const deleteOldCaches = async () => {
const keyList = await caches.keys();
const cachesToDelete = keyList.filter((key) => !CACHE_VER.includes(key));
await Promise.all(cachesToDelete.map(deleteCache));
};
const putInCache = async (request, response) => {
const cache = await caches.open(CACHE_VER);
await cache.put(request, response);
};
const cacheMatch = async (request) => {
const requestUrl = request.url;
const responseFromCache = await caches.match(request);
if (responseFromCache) {
// console.log("Find Cache! Return! URL: "+requestUrl);
return responseFromCache;
}
if (requestUrl.includes("assets/video/loop.mp4") && await caches.match(request)) {
// console.log("Video URL!");
await caches.open(CACHE_VER).then(function (cache) {
return cache.addAll([
'./assets/video/loop.mp4'
]);
});
}
const responseFromNet = await fetch(request);
if (!requestUrl.includes('assets/video/loop.mp4') && !requestUrl.includes('api') && !requestUrl.includes('hitokoto')) {
// console.log("Matched! URL: " + requestUrl);
putInCache(request, responseFromNet.clone());
}
return responseFromNet;
};
this.addEventListener('install', function (event) {
event.waitUntil(cacheInit());
});
this.addEventListener('activate', function (event) {
event.waitUntil(deleteOldCaches());
});
this.addEventListener('fetch', function (event) {
event.respondWith(cacheMatch(event.request));
});