From e76c8d11fd84f7f6de6c5684052016a9b2152bf3 Mon Sep 17 00:00:00 2001 From: bender Date: Tue, 10 Mar 2026 16:42:13 +0000 Subject: [PATCH] Add public/sw.js --- public/sw.js | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 public/sw.js diff --git a/public/sw.js b/public/sw.js new file mode 100644 index 0000000..1c5c892 --- /dev/null +++ b/public/sw.js @@ -0,0 +1,68 @@ +const CACHE_VERSION = 'v1'; +const CACHE_NAME = `portfolio-cache-${CACHE_VERSION}`; + +const URLS_TO_CACHE = [ + '/', + '/index.html', + '/manifest.json' +]; + +self.addEventListener('install', (event) => { + event.waitUntil( + caches.open(CACHE_NAME).then((cache) => { + return cache.addAll(URLS_TO_CACHE); + }) + ); + self.skipWaiting(); +}); + +self.addEventListener('activate', (event) => { + event.waitUntil( + caches.keys().then((cacheNames) => { + return Promise.all( + cacheNames + .filter((cacheName) => cacheName !== CACHE_NAME) + .map((cacheName) => caches.delete(cacheName)) + ); + }) + ); + self.clients.claim(); +}); + +self.addEventListener('fetch', (event) => { + const { request } = event; + const url = new URL(request.url); + + if (request.method !== 'GET') { + return; + } + + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + return; + } + + event.respondWith( + caches.match(request).then((cachedResponse) => { + if (cachedResponse) { + return cachedResponse; + } + + return fetch(request) + .then((response) => { + if (!response || response.status !== 200 || response.type === 'error') { + return response; + } + + const responseToCache = response.clone(); + caches.open(CACHE_NAME).then((cache) => { + cache.put(request, responseToCache); + }); + + return response; + }) + .catch(() => { + return caches.match('/index.html'); + }); + }) + ); +});