Skip to content

Commit

Permalink
Updated service worker
Browse files Browse the repository at this point in the history
  • Loading branch information
moiskillnadne committed Jan 14, 2025
1 parent c346f8b commit 2c6cff8
Showing 1 changed file with 42 additions and 12 deletions.
54 changes: 42 additions & 12 deletions public/service-worker.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,50 @@
// service-worker.ts
const CACHE_NAME = 'app-cache-v1'
const STATIC_CACHE_NAME = 'static-cache-v1'

async function getAssetsFromManifest() {
const manifest = await fetch('/manifest.json').then((response) => response.json())
const assets = Object.values(manifest).map((entry) => entry.file)
return assets
try {
const response = await fetch('/manifest.json')
if (!response.ok) throw new Error('Failed to fetch manifest')
const manifest = await response.json()
return Object.values(manifest).map((entry) => entry.file)
} catch (error) {
console.error('Error fetching manifest:', error)
return []
}
}

self.addEventListener('install', (event) => {
event.waitUntil(
(async () => {
const cache = await caches.open('app-cache')
const cache = await caches.open(CACHE_NAME)
const assets = await getAssetsFromManifest()
cache.addAll(['/', '/index.html', ...assets])
try {
await cache.addAll(['/', '/index.html', ...assets])
console.log('Assets cached successfully')
} catch (error) {
console.error('Error caching assets:', error)
}
})(),
)
})

self.addEventListener('activate', (event) => {
event.waitUntil(
(async () => {
const cacheNames = await caches.keys()
await Promise.all(
cacheNames
.filter((name) => name !== CACHE_NAME && name !== STATIC_CACHE_NAME)
.map((name) => caches.delete(name)),
)
console.log('Old caches cleared')
})(),
)
})

self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url)

// Static resources are cached
const isStaticResource =
url.pathname.endsWith('.html') ||
url.pathname.endsWith('.css') ||
Expand All @@ -34,15 +59,20 @@ self.addEventListener('fetch', (event) => {
if (isStaticResource && !isApiRequest) {
event.respondWith(
caches.match(event.request).then((cachedResponse) => {
return (
cachedResponse ||
fetch(event.request).then((networkResponse) => {
return caches.open('static-cache').then((cache) => {
if (cachedResponse) {
return cachedResponse
}
return fetch(event.request)
.then((networkResponse) => {
return caches.open(STATIC_CACHE_NAME).then((cache) => {
cache.put(event.request, networkResponse.clone())
return networkResponse
})
})
)
.catch((error) => {
console.error('Fetch failed:', error)
throw error
})
}),
)
}
Expand Down

0 comments on commit 2c6cff8

Please sign in to comment.