posimai-tech-events/sw.js

53 lines
1.6 KiB
JavaScript
Raw Normal View History

const CACHE_NAME = 'posimai-tech-events-v4';
const STATIC_ASSETS = ['/', '/index.html', '/manifest.json', '/logo.png'];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME).then(cache => cache.addAll(STATIC_ASSETS))
);
self.skipWaiting();
});
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(keys =>
Promise.all(
keys.filter(k => k !== CACHE_NAME).map(k => caches.delete(k))
)
)
);
self.clients.claim();
});
self.addEventListener('fetch', event => {
const url = new URL(event.request.url);
// API: network first, fallback to cache
if (url.pathname.startsWith('/api/')) {
event.respondWith(
fetch(event.request)
.then(response => {
const clone = response.clone();
caches.open(CACHE_NAME).then(cache => cache.put(event.request, clone));
return response;
})
.catch(() => caches.match(event.request))
);
return;
}
// Static: cache first, fallback to network
event.respondWith(
caches.match(event.request).then(cached => {
if (cached) return cached;
return fetch(event.request).then(response => {
if (response.ok) {
const clone = response.clone();
caches.open(CACHE_NAME).then(cache => cache.put(event.request, clone));
}
return response;
});
})
);
});