Spaces:
Running
Running
Add service worker
Browse files- public/sw.js +49 -0
public/sw.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Service worker: precache the app shell and engine so the app opens offline.
|
| 2 |
+
// Same-origin only; model + voice files are cached by phonon-tts itself.
|
| 3 |
+
const VERSION = '__VERSION__';
|
| 4 |
+
const PRECACHE = __PRECACHE__;
|
| 5 |
+
const CACHE = 'reader-shell-' + VERSION;
|
| 6 |
+
|
| 7 |
+
self.addEventListener('install', (event) => {
|
| 8 |
+
event.waitUntil(
|
| 9 |
+
caches.open(CACHE).then((c) => c.addAll(PRECACHE)).then(() => self.skipWaiting())
|
| 10 |
+
);
|
| 11 |
+
});
|
| 12 |
+
|
| 13 |
+
self.addEventListener('activate', (event) => {
|
| 14 |
+
event.waitUntil(
|
| 15 |
+
caches.keys()
|
| 16 |
+
.then((keys) => Promise.all(
|
| 17 |
+
keys.filter((k) => k.startsWith('reader-shell-') && k !== CACHE).map((k) => caches.delete(k))
|
| 18 |
+
))
|
| 19 |
+
.then(() => self.clients.claim())
|
| 20 |
+
);
|
| 21 |
+
});
|
| 22 |
+
|
| 23 |
+
self.addEventListener('fetch', (event) => {
|
| 24 |
+
const req = event.request;
|
| 25 |
+
if (req.method !== 'GET') return;
|
| 26 |
+
const url = new URL(req.url);
|
| 27 |
+
if (url.origin !== self.location.origin) return;
|
| 28 |
+
|
| 29 |
+
// Page navigations (including share-target URLs with ?text=...): serve the
|
| 30 |
+
// cached shell, so it works offline; the query string is read client-side.
|
| 31 |
+
if (req.mode === 'navigate') {
|
| 32 |
+
event.respondWith(
|
| 33 |
+
caches.open(CACHE).then(async (c) =>
|
| 34 |
+
(await c.match('./index.html')) || (await c.match('./')) || fetch(req)
|
| 35 |
+
)
|
| 36 |
+
);
|
| 37 |
+
return;
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
event.respondWith(
|
| 41 |
+
caches.open(CACHE).then(async (c) => {
|
| 42 |
+
const hit = await c.match(req, { ignoreSearch: true });
|
| 43 |
+
if (hit) return hit;
|
| 44 |
+
const res = await fetch(req);
|
| 45 |
+
if (res.ok) c.put(req, res.clone());
|
| 46 |
+
return res;
|
| 47 |
+
})
|
| 48 |
+
);
|
| 49 |
+
});
|