// sw.js - Service Worker Script
const CACHE_NAME = 'v1-cache';
const urlsToCache = [
'/',
'/index.html',
'/styles.css',
'/app.js'
// Add more assets here
];
// Install: Cache assets at startup (precache)
self.addEventListener('install', event => {
console.log('SW: Installing...');
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => {
console.log('SW: Caching assets');
return cache.addAll(urlsToCache);
})
);
});
// Activate: Clean up old caches
self.addEventListener('activate', event => {
console.log('SW: Activating...');
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheName !== CACHE_NAME) {
console.log('SW: Deleting old cache:', cacheName);
return caches.delete(cacheName);
}
})
);
})
);
});
// Fetch: Cache-first (stale response), validate/update from server in background
self.addEventListener('fetch', event => {
// Skip non-GET or non-same-origin (adjust as needed)
if (event.request.method !== 'GET') return;
event.respondWith(
caches.match(event.request)
.then(cachedResponse => {
if (cachedResponse) {
// Cache hit: Return cached (stale-while-revalidate)
// Validate against server in background
fetchAndUpdateCache(event.request, cachedResponse.clone());
return cachedResponse;
} else {
// Cache miss: Fetch from network
return fetch(event.request).then(networkResponse => {
if (!networkResponse || networkResponse.status !== 200 || networkResponse.type !== 'basic') {
return networkResponse;
}
// Cache the network response
const responseToCache = networkResponse.clone();
caches.open(CACHE_NAME).then(cache => {
cache.put(event.request, responseToCache);
});
return networkResponse;
}).catch(() => {
// Network error: Offline, no fallback for demo
console.log('SW: Offline, no cache hit.');
});
}
})
);
});
// Helper: Fetch from server and update cache if newer (validates via full fetch)
function fetchAndUpdateCache(request, oldResponse) {
fetch(request).then(networkResponse => {
if (!networkResponse || networkResponse.status !== 200 || networkResponse.type !== 'basic') {
return Promise.resolve(null);
}
// Compare ETag/Last-Modified for true validation (optional enhancement)
const networkHeaders = networkResponse.headers;
const oldHeaders = oldResponse.headers;
const networkETag = networkHeaders.get('etag');
const oldETag = oldHeaders.get('etag');
const networkLastMod = networkHeaders.get('last-modified');
const oldLastMod = oldHeaders.get('last-modified');
let isStale = true; // Assume stale unless proven fresh
if (networkETag && oldETag && networkETag === oldETag) {
isStale = false;
} else if (networkLastMod && oldLastMod && networkLastMod === oldLastMod) {
isStale = false;
}
if (isStale) {
console.log('SW: Cache stale; updating from server');
const responseToCache = networkResponse.clone();
caches.open(CACHE_NAME).then(cache => {
cache.put(request, responseToCache);
});
} else {
console.log('SW: Cache fresh');
}
}).catch(() => {
console.log('SW: Validation fetch failed (offline)');
});
}