Files

103 lines
2.5 KiB
JavaScript

const CACHE_PREFIX = 'mengyadriftbottle'
const CACHE_VERSION = 'v1'
const STATIC_CACHE = `${CACHE_PREFIX}-static-${CACHE_VERSION}`
const RUNTIME_CACHE = `${CACHE_PREFIX}-runtime-${CACHE_VERSION}`
const PRECACHE_URLS = [
'/',
'/index.html',
'/offline.html',
'/manifest.webmanifest',
'/logo.png',
'/logo3.png',
]
self.addEventListener('install', (event) => {
event.waitUntil(
(async () => {
const cache = await caches.open(STATIC_CACHE)
await cache.addAll(PRECACHE_URLS)
self.skipWaiting()
})(),
)
})
self.addEventListener('activate', (event) => {
event.waitUntil(
(async () => {
const keys = await caches.keys()
await Promise.all(
keys.map((key) => {
if (
key.startsWith(`${CACHE_PREFIX}-`) &&
key !== STATIC_CACHE &&
key !== RUNTIME_CACHE
) {
return caches.delete(key)
}
return undefined
}),
)
await self.clients.claim()
})(),
)
})
self.addEventListener('message', (event) => {
if (event?.data?.type === 'SKIP_WAITING') {
self.skipWaiting()
}
})
function isSameOrigin(url) {
return url.origin === self.location.origin
}
self.addEventListener('fetch', (event) => {
const { request } = event
if (request.method !== 'GET') return
const url = new URL(request.url)
if (!isSameOrigin(url)) return
if (url.pathname.startsWith('/api')) return
if (request.mode === 'navigate') {
event.respondWith(
(async () => {
try {
const networkResponse = await fetch(request)
const cache = await caches.open(RUNTIME_CACHE)
cache.put('/index.html', networkResponse.clone())
return networkResponse
} catch {
const cache = await caches.open(RUNTIME_CACHE)
const cached =
(await cache.match('/index.html')) ||
(await caches.match('/index.html')) ||
(await caches.match('/offline.html'))
return cached || Response.error()
}
})(),
)
return
}
const isAsset = ['script', 'style', 'image', 'font'].includes(request.destination)
if (isAsset) {
event.respondWith(
(async () => {
const cached = await caches.match(request)
if (cached) return cached
const response = await fetch(request)
const cache = await caches.open(RUNTIME_CACHE)
cache.put(request, response.clone())
return response
})(),
)
return
}
})