forked from Track-Gen/TrackGen
-
Notifications
You must be signed in to change notification settings - Fork 3
/
service-worker.js
97 lines (85 loc) · 2.93 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
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
94
95
96
97
const appPrefix = 'TrackGen';
const appVersion = 'v1.0.7';
const cacheName = `${appPrefix}-${appVersion}`;
const foldersToCache = ['media', 'js', 'css'];
const additionalCache = ['/', 'manifest.json', 'index.html'];
let filesToCache = [];
async function generateFilesToCache() {
filesToCache = [];
for (const folder of foldersToCache) {
try {
const response = await fetch(`/${folder}/`);
if (!response.ok) {
console.error(`Failed to fetch ${folder} folder: ${response.statusText}`);
continue;
}
const folderFiles = await response.text();
const regex = /href="([^"]+\.(png|jpg|jpeg|jxl|webp|js|css))"/g;
let match;
while ((match = regex.exec(folderFiles)) !== null) {
if (match[1] !== 'bg16383.webp') {
filesToCache.push(`/${folder}/${match[1]}`);
}
}
} catch (error) {
console.error(`Error fetching files from ${folder}:`, error);
}
}
filesToCache.push(...additionalCache);
return filesToCache;
}
function isCachable(request) {
const url = new URL(request.url);
return filesToCache && url.origin === location.origin && filesToCache.includes(url.pathname);
}
async function cacheFirstWithRefresh(request) {
try {
const fetchResponsePromise = fetch(request).then(async networkResponse => {
if (networkResponse.ok) {
const cache = await caches.open(cacheName);
cache.put(request, networkResponse.clone());
}
console.log(`Fetched URL ${request.url} from network.`);
return networkResponse;
});
return Promise.race([
fetchResponsePromise,
caches.match(request)
]);
} catch (error) {
console.error(`Failed to fetch ${request.url} from cache or network.`);
throw error;
}
}
self.addEventListener('install', event => {
event.waitUntil(
generateFilesToCache().then(files => {
return caches.open(cacheName).then(cache => {
return cache.addAll(files);
});
}).catch(error => {
console.error('Failed to generate files to cache:', error);
})
);
});
self.addEventListener("fetch", async (event) => {
const request = event.request;
if (isCachable(request)) {
event.respondWith(cacheFirstWithRefresh(request));
} else {
event.respondWith(fetch(request));
}
});
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.filter(cacheName => {
return cacheName.startsWith(appPrefix) && cacheName !== cacheName;
}).map(cacheName => {
return caches.delete(cacheName);
})
);
})
);
});