public/sw.js (view raw)
1// Service Worker for PWA support
2const CACHE_NAME = 'clicker-game-cache-v1';
3const urlsToCache = [
4 '/',
5 '/index.html',
6 '/favicon.svg',
7 '/manifest.json',
8 '/icons/icon-192x192.png',
9 '/icons/icon-512x512.png'
10];
11
12// Install the service worker and cache assets
13self.addEventListener('install', (event) => {
14 event.waitUntil(
15 caches.open(CACHE_NAME)
16 .then((cache) => {
17 return cache.addAll(urlsToCache);
18 })
19 );
20});
21
22// Activate and clean up old caches
23self.addEventListener('activate', (event) => {
24 event.waitUntil(
25 caches.keys().then((cacheNames) => {
26 return Promise.all(
27 cacheNames.map((cacheName) => {
28 if (cacheName !== CACHE_NAME) {
29 return caches.delete(cacheName);
30 }
31 })
32 );
33 })
34 );
35});
36
37// Serve cached content when offline
38self.addEventListener('fetch', (event) => {
39 event.respondWith(
40 caches.match(event.request)
41 .then((response) => {
42 // Cache hit - return the response from the cached version
43 if (response) {
44 return response;
45 }
46
47 // Not in cache - fetch from network
48 return fetch(event.request).then(
49 (response) => {
50 // Check if we received a valid response
51 if (!response || response.status !== 200 || response.type !== 'basic') {
52 return response;
53 }
54
55 // Clone the response
56 const responseToCache = response.clone();
57
58 // Add to cache for future use
59 caches.open(CACHE_NAME)
60 .then((cache) => {
61 cache.put(event.request, responseToCache);
62 });
63
64 return response;
65 }
66 );
67 })
68 );
69});