73 lines
1.7 KiB
JavaScript
73 lines
1.7 KiB
JavaScript
const CACHE_NAME = 'agromonev-v1';
|
|
|
|
// asset statis saja
|
|
const STATIC_ASSETS = [
|
|
'/',
|
|
'/offline',
|
|
];
|
|
|
|
// install
|
|
self.addEventListener('install', event => {
|
|
self.skipWaiting();
|
|
event.waitUntil(
|
|
caches.open(CACHE_NAME)
|
|
.then(cache => cache.addAll(STATIC_ASSETS))
|
|
);
|
|
});
|
|
|
|
// activate (hapus cache lama)
|
|
self.addEventListener('activate', event => {
|
|
event.waitUntil(
|
|
caches.keys().then(keys => {
|
|
return Promise.all(
|
|
keys.map(key => {
|
|
if (key !== CACHE_NAME) {
|
|
return caches.delete(key);
|
|
}
|
|
})
|
|
);
|
|
})
|
|
);
|
|
self.clients.claim();
|
|
});
|
|
|
|
self.addEventListener('fetch', event => {
|
|
const request = event.request;
|
|
|
|
if (!request.url.startsWith('http')) return;
|
|
if (request.method !== 'GET') return;
|
|
|
|
const url = new URL(request.url);
|
|
|
|
// ❗ SKIP halaman auth & dashboard
|
|
if (
|
|
url.pathname.startsWith('/login') ||
|
|
url.pathname.startsWith('/logout') ||
|
|
url.pathname.startsWith('/register') ||
|
|
url.pathname.startsWith('/dashboard') ||
|
|
url.pathname.startsWith('/admin')
|
|
) {
|
|
event.respondWith(fetch(request));
|
|
return;
|
|
}
|
|
|
|
// ❗ SKIP API
|
|
if (url.pathname.startsWith('/api')) {
|
|
event.respondWith(fetch(request));
|
|
return;
|
|
}
|
|
|
|
// 🔹 HTML → network first
|
|
if (request.headers.get('accept')?.includes('text/html')) {
|
|
event.respondWith(
|
|
fetch(request)
|
|
.catch(() => caches.match('/offline'))
|
|
);
|
|
return;
|
|
}
|
|
|
|
// 🔹 asset → cache
|
|
event.respondWith(
|
|
caches.match(request).then(res => res || fetch(request))
|
|
);
|
|
}); |