39 lines
1.4 KiB
JavaScript
39 lines
1.4 KiB
JavaScript
|
|
// Posimai SW — stale-while-revalidate + update notification
|
||
|
|
// バージョンは index.html に inline で管理(この文字列変更で旧キャッシュ削除)
|
||
|
|
const CACHE = 'APP_ID-v2';
|
||
|
|
const STATIC = ['/', '/index.html', '/manifest.json', '/logo.png'];
|
||
|
|
|
||
|
|
self.addEventListener('install', e => {
|
||
|
|
e.waitUntil(
|
||
|
|
caches.open(CACHE).then(c => c.addAll(STATIC))
|
||
|
|
// skipWaiting() は意図的に呼ばない
|
||
|
|
// → updatefound イベントで UI 側からユーザーに通知する方式を採用
|
||
|
|
);
|
||
|
|
});
|
||
|
|
|
||
|
|
self.addEventListener('activate', e => {
|
||
|
|
e.waitUntil(
|
||
|
|
caches.keys().then(keys =>
|
||
|
|
Promise.all(keys.filter(k => k !== CACHE).map(k => caches.delete(k)))
|
||
|
|
).then(() => self.clients.claim())
|
||
|
|
);
|
||
|
|
});
|
||
|
|
|
||
|
|
self.addEventListener('fetch', e => {
|
||
|
|
if (e.request.method !== 'GET') return;
|
||
|
|
if (!e.request.url.startsWith(self.location.origin)) return;
|
||
|
|
|
||
|
|
e.respondWith(
|
||
|
|
caches.open(CACHE).then(cache =>
|
||
|
|
cache.match(e.request).then(cached => {
|
||
|
|
const network = fetch(e.request).then(res => {
|
||
|
|
if (res.ok && res.type === 'basic') cache.put(e.request, res.clone());
|
||
|
|
return res;
|
||
|
|
}).catch(() => cached);
|
||
|
|
// stale-while-revalidate: キャッシュがあればすぐ返し、裏でネットワーク更新
|
||
|
|
return cached || network;
|
||
|
|
})
|
||
|
|
)
|
||
|
|
);
|
||
|
|
});
|