File size: 3,079 Bytes
b42373a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | /* ==========================================================================
CHASSIS OCR PWA - SERVICE WORKER
========================================================================== */
const CACHE_NAME = 'chassis-ocr-pwa-v1';
const ASSETS_TO_CACHE = [
'/',
'/index.html',
'/app.css',
'/app.js',
'/manifest.json',
'/icons/icon-192.png',
'/icons/icon-512.png'
];
// Install Service Worker and Cache Assets
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME)
.then((cache) => {
console.log('[Service Worker] Caching App Shell...');
return cache.addAll(ASSETS_TO_CACHE);
})
.then(() => self.skipWaiting())
);
});
// Activate event (clean up old caches)
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((keyList) => {
return Promise.all(keyList.map((key) => {
if (key !== CACHE_NAME) {
console.log('[Service Worker] Removing old cache:', key);
return caches.delete(key);
}
}));
}).then(() => self.clients.claim())
);
});
// Fetch events (Network-first with Cache Fallback for API / Cache-first for Assets)
self.addEventListener('fetch', (event) => {
const requestUrl = new URL(event.request.url);
// Bypass caching for backend API requests and other HTTP methods (POST, PUT, DELETE)
if (event.request.method !== 'GET' || requestUrl.pathname.startsWith('/api/')) {
return;
}
event.respondWith(
caches.match(event.request)
.then((cachedResponse) => {
if (cachedResponse) {
// Serve cached asset immediately, but fetch fresh version in the background
fetch(event.request).then((networkResponse) => {
if (networkResponse && networkResponse.status === 200) {
caches.open(CACHE_NAME).then((cache) => {
cache.put(event.request, networkResponse);
});
}
}).catch(() => {/* Ignore network failures in background */});
return cachedResponse;
}
// If not cached, fetch from network
return fetch(event.request).then((networkResponse) => {
if (!networkResponse || networkResponse.status !== 200 || networkResponse.type !== 'basic') {
return networkResponse;
}
// Cache the newly fetched asset
const responseToCache = networkResponse.clone();
caches.open(CACHE_NAME).then((cache) => {
cache.put(event.request, responseToCache);
});
return networkResponse;
});
})
);
});
|