// A name for our cache, change this every time you update the app shell const CACHE_NAME = 'timetracker-v2'; // The files that make up the "app shell" const urlsToCache = [ '/', '/index.html', 'https://cdn.tailwindcss.com', 'https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap' ]; // 1. Installation: Open the cache and add the app shell files. self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME) .then((cache) => { console.log('Opened cache and added app shell'); return cache.addAll(urlsToCache); }) ); }); // 2. Activation: Clean up old caches. (NEW) // This event fires after install and when the new service worker takes control. self.addEventListener('activate', (event) => { event.waitUntil( caches.keys().then((cacheNames) => { return Promise.all( cacheNames.map((cacheName) => { // If a cache is not the current one, delete it. if (cacheName !== CACHE_NAME) { console.log('Deleting old cache:', cacheName); return caches.delete(cacheName); } }) ); }) ); }); // 3. Fetch: Serve from cache, fallback to network, and cache new requests. (IMPROVED) self.addEventListener('fetch', (event) => { // We only want to cache GET requests if (event.request.method !== 'GET') { return; } event.respondWith( caches.match(event.request) .then((cachedResponse) => { // If the response is in the cache, return it. if (cachedResponse) { return cachedResponse; } // If not in cache, go to the network. return fetch(event.request).then((networkResponse) => { // If the network request is successful, cache it for next time. if (networkResponse && networkResponse.status === 200) { const responseToCache = networkResponse.clone(); // Clone the response caches.open(CACHE_NAME) .then((cache) => { cache.put(event.request, responseToCache); }); } return networkResponse; }); }) ); });