notes
All repositories: gitoria
1.6 KB
// sw.js — the service worker of notes.worldapi.org (ticket notes#2): the app opens without a network.// NETWORK FIRST: every page and asset is fetched as usual and the answer is kept; with no network the kept copy// answers. A page (`/` or `/note/<id>`) is kept once, under '/shell': the page carries no note data (the notes come// from the browser's IndexedDB, /notes-offline.js), so one page serves every note. The API and the socket are never// touched here. /notes-offline.js also puts the page and the assets it was loaded with into the same cache.const CACHE = 'notes-shell-v1';const isPage = (url) => url.pathname === '/' || url.pathname.startsWith('/note/');self.addEventListener('install', () => self.skipWaiting());self.addEventListener('activate', (e) => e.waitUntil((async () => {for (const k of await caches.keys()) if (k !== CACHE) await caches.delete(k);await self.clients.claim();})()));self.addEventListener('fetch', (e) => {const req = e.request;const url = new URL(req.url);if (req.method !== 'GET' || url.origin !== self.location.origin) return;if (url.pathname.startsWith('/api/') || url.pathname.startsWith('/login/')) return;if (req.mode === 'navigate' && !isPage(url)) return;e.respondWith((async () => {const cache = await caches.open(CACHE);const key = req.mode === 'navigate' ? '/shell' : req.url;try {const res = await fetch(req);if (res.ok && !res.redirected && res.type === 'basic') cache.put(key, res.clone());return res;} catch (err) {const kept = await cache.match(key);if (kept) return kept;throw err;}})());});
Branches
- mainmain branch