sw.js raw

   1  const CACHE_VERSION = 'orly-v4';
   2  const STATIC_ASSETS = [
   3    '/',
   4    '/index.html',
   5    '/bundle.js',
   6    '/bundle.css',
   7    '/global.css',
   8    '/favicon.png',
   9    '/icon-192.png',
  10    '/icon-512.png',
  11    '/orly.png'
  12  ];
  13  
  14  self.addEventListener('install', (event) => {
  15    event.waitUntil(
  16      caches.open(CACHE_VERSION).then((cache) => {
  17        return cache.addAll(STATIC_ASSETS);
  18      })
  19    );
  20    self.skipWaiting();
  21  });
  22  
  23  self.addEventListener('activate', (event) => {
  24    event.waitUntil(
  25      caches.keys().then((cacheNames) => {
  26        return Promise.all(
  27          cacheNames
  28            .filter((name) => name !== CACHE_VERSION)
  29            .map((name) => caches.delete(name))
  30        );
  31      })
  32    );
  33    self.clients.claim();
  34  });
  35  
  36  self.addEventListener('fetch', (event) => {
  37    const url = new URL(event.request.url);
  38  
  39    // Skip WebSocket requests
  40    if (url.protocol === 'ws:' || url.protocol === 'wss:') {
  41      return;
  42    }
  43  
  44    // Skip non-GET requests
  45    if (event.request.method !== 'GET') {
  46      return;
  47    }
  48  
  49    // API calls: network-first with cache fallback
  50    if (url.pathname.startsWith('/api/')) {
  51      event.respondWith(
  52        fetch(event.request)
  53          .then((response) => {
  54            if (response.ok) {
  55              const clone = response.clone();
  56              caches.open(CACHE_VERSION).then((cache) => {
  57                cache.put(event.request, clone);
  58              });
  59            }
  60            return response;
  61          })
  62          .catch(() => {
  63            return caches.match(event.request);
  64          })
  65      );
  66      return;
  67    }
  68  
  69    // Static assets: cache-first with network fallback
  70    event.respondWith(
  71      caches.match(event.request).then((cached) => {
  72        if (cached) {
  73          // Update cache in background
  74          fetch(event.request).then((response) => {
  75            if (response.ok) {
  76              caches.open(CACHE_VERSION).then((cache) => {
  77                cache.put(event.request, response);
  78              });
  79            }
  80          }).catch(() => {});
  81          return cached;
  82        }
  83  
  84        return fetch(event.request).then((response) => {
  85          if (response.ok) {
  86            const clone = response.clone();
  87            caches.open(CACHE_VERSION).then((cache) => {
  88              cache.put(event.request, clone);
  89            });
  90          }
  91          return response;
  92        });
  93      })
  94    );
  95  });
  96