|
| 1 | +// service-worker.js |
| 2 | + |
| 3 | +const CACHE_NAME = "prasad-blogfolio-v1"; |
| 4 | +const urlsToCache = [ |
| 5 | + "/", |
| 6 | + "/index.html", |
| 7 | + "/blog/", |
| 8 | + "/assets/main.css", |
| 9 | + // Add other static assets (images, fonts, scripts) that you want to cache here. |
| 10 | +]; |
| 11 | + |
| 12 | +// Install the service worker |
| 13 | +self.addEventListener("install", (event) => { |
| 14 | + event.waitUntil( |
| 15 | + caches.open(CACHE_NAME).then((cache) => { |
| 16 | + console.log("Cache opened"); |
| 17 | + return cache.addAll(urlsToCache); |
| 18 | + }) |
| 19 | + ); |
| 20 | +}); |
| 21 | + |
| 22 | +// Fetch cached assets when offline |
| 23 | +self.addEventListener("fetch", (event) => { |
| 24 | + event.respondWith( |
| 25 | + caches.match(event.request).then((response) => { |
| 26 | + // Cache hit - return response |
| 27 | + if (response) { |
| 28 | + return response; |
| 29 | + } |
| 30 | + |
| 31 | + // Not in cache - fetch from network |
| 32 | + return fetch(event.request).then((networkResponse) => { |
| 33 | + // Check if the request was successful |
| 34 | + if ( |
| 35 | + !networkResponse || |
| 36 | + networkResponse.status !== 200 || |
| 37 | + networkResponse.type !== "basic" |
| 38 | + ) { |
| 39 | + return networkResponse; |
| 40 | + } |
| 41 | + |
| 42 | + // Response is good - add it to the cache |
| 43 | + const responseToCache = networkResponse.clone(); |
| 44 | + |
| 45 | + caches.open(CACHE_NAME).then((cache) => { |
| 46 | + cache.put(event.request, responseToCache); |
| 47 | + }); |
| 48 | + return networkResponse; |
| 49 | + }); |
| 50 | + }) |
| 51 | + ); |
| 52 | +}); |
| 53 | + |
| 54 | +// Activate the service worker and remove old caches |
| 55 | +self.addEventListener("activate", (event) => { |
| 56 | + const cacheWhitelist = [CACHE_NAME]; |
| 57 | + event.waitUntil( |
| 58 | + caches.keys().then((cacheNames) => |
| 59 | + Promise.all( |
| 60 | + cacheNames.map((cacheName) => { |
| 61 | + if (!cacheWhitelist.includes(cacheName)) { |
| 62 | + return caches.delete(cacheName); |
| 63 | + } |
| 64 | + }) |
| 65 | + ) |
| 66 | + ) |
| 67 | + ); |
| 68 | +}); |
0 commit comments