-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
65 lines (62 loc) · 2.28 KB
/
sw.js
File metadata and controls
65 lines (62 loc) · 2.28 KB
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
// Service worker: caches the app shell for offline use and updates cache on fetch.
const CACHE_PREFIX = 'read-txt-';
const CACHE_NAME = 'read-txt-v6';
// Pre-cache the core app shell for offline use.
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll([
'./',
'./index.html',
'./style.css',
'./js/app.js',
'./js/ui.js',
'./js/storage.js',
'./js/speech.js',
'./manifest.webmanifest',
'./icons/android-chrome-192x192.png',
'./icons/android-chrome-512x512.png',
'./icons/apple-touch-icon.png',
'./icons/favicon-32x32.png',
'./icons/favicon-16x16.png',
'./icons/favicon.ico'
]);
})
);
self.skipWaiting();
});
// Clear old caches when a new service worker activates.
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((keys) => {
const keysToDelete = keys.filter((key) => key.startsWith(CACHE_PREFIX) && key !== CACHE_NAME);
return Promise.all(keysToDelete.map((key) => caches.delete(key)));
})
);
self.clients.claim();
});
// Network-first fetch with cache fallback.
self.addEventListener('fetch', (event) => {
if (event.request.method !== 'GET') return;
const url = new URL(event.request.url);
if (url.protocol !== 'http:' && url.protocol !== 'https:') return;
event.respondWith(
fetch(event.request)
.then((networkResponse) => {
if (!networkResponse.ok) {
return networkResponse;
}
const responseClone = networkResponse.clone();
caches
.open(CACHE_NAME)
.then((cache) => cache.put(event.request, responseClone))
.catch((error) => {
console.error('Failed to update cache for request:', event.request.url, error);
});
return networkResponse;
})
.catch(() => {
return caches.match(event.request);
})
);
});