Files
stemengine_old/frontend/public/sw.js
T
2026-03-03 14:52:19 +09:00

60 lines
1.7 KiB
JavaScript
Executable File

// StemEngine Service Worker
// Minimal implementation for PWA installability.
// API responses are intentionally NOT cached (all data is dynamic/local).
// The app shell (HTML/JS/CSS) is cached so the UI loads instantly on repeat visits.
const CACHE = 'stemengine-v1'
// Assets to pre-cache on install
const SHELL = ['/']
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE).then((cache) => cache.addAll(SHELL))
)
// Activate immediately — don't wait for old tabs to close
self.skipWaiting()
})
self.addEventListener('activate', (event) => {
// Delete old caches from previous versions
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))
).then(() => self.clients.claim())
)
})
self.addEventListener('fetch', (event) => {
const { request } = event
const url = new URL(request.url)
// Let API calls and non-GET requests go straight to the network
if (request.method !== 'GET' || url.pathname.startsWith('/api/')) {
event.respondWith(fetch(request))
return
}
// For navigation requests: network-first, fall back to cached shell
if (request.mode === 'navigate') {
event.respondWith(
fetch(request).catch(() => caches.match('/'))
)
return
}
// For static assets: cache-first
event.respondWith(
caches.match(request).then((cached) => {
if (cached) return cached
return fetch(request).then((response) => {
if (response.ok) {
const clone = response.clone()
caches.open(CACHE).then((cache) => cache.put(request, clone))
}
return response
})
})
)
})