diff --git a/articles/index.html b/articles/index.html index 638e8b5..08aca40 100644 --- a/articles/index.html +++ b/articles/index.html @@ -4,7 +4,6 @@ Mini Articles @@ -241,6 +237,8 @@ article h1{margin:.25rem 0 .5rem;font-size:1.6rem} show(listV); setLoading(false); })(); + + navigator.serviceWorker&&navigator.serviceWorker.register('/sw.js').catch(()=>{}); })(); diff --git a/articles/sw.js b/articles/sw.js new file mode 100644 index 0000000..7842990 --- /dev/null +++ b/articles/sw.js @@ -0,0 +1,18 @@ +// Minimal image cache-first service worker +const C = 'articles-img-v1'; +self.addEventListener('install', e => self.skipWaiting()); +self.addEventListener('activate', e => e.waitUntil(self.clients.claim())); +self.addEventListener('fetch', e => { + const req = e.request; + const u = new URL(req.url); + const isImg = req.destination === 'image' || u.pathname.startsWith('/uploads/'); + if (!isImg || req.method !== 'GET') return; + e.respondWith((async () => { + const cache = await caches.open(C); + const hit = await cache.match(req, { ignoreVary: true, ignoreSearch: false }); + if (hit) return hit; + const res = await fetch(req); + if (res && res.ok) cache.put(req, res.clone()); + return res; + })()); +});