Created
May 28, 2023 09:38
-
-
Save Akash52/608faa584ebbaee7aeb7c4a6c1bc388d to your computer and use it in GitHub Desktop.
serviceworker.js for svelte
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { build, files } from '$service-worker'; | |
const worker = self; | |
const STATIC_CACHE_NAME = 'cache-v1'; | |
const APP_CACHE_NAME = 'offline-v1'; | |
const CACHE_NAMES = [STATIC_CACHE_NAME, APP_CACHE_NAME]; | |
const version = 'v1'; | |
// hard-coded list of app routes we want to preemptively cache | |
const routes = ['/']; | |
// hard-coded list of other assets necessary for page load outside our domain | |
const customAssets = ['https://fonts.googleapis.com/css2?family=Poppins:wght@400;700&display=swap']; | |
// `build` is an array of all the files generated by the bundler, | |
const addOrigin = (assets) => assets.map((asset) => `${self.location.origin}${asset}`); | |
// Filter out logos for iOS and add origin to assets | |
const ourAssets = addOrigin([ | |
...files.filter((file) => !/\/icons\/(apple.*?|original.png)/.test(file)), | |
...build, | |
...routes | |
]); | |
// Combine our assets and custom assets to be pre-cached | |
const toCache = [...ourAssets, ...customAssets]; | |
async function cacheStaticAssets() { | |
const cache = await caches.open(STATIC_CACHE_NAME); | |
await cache.addAll(toCache); | |
} | |
async function deleteOldCaches() { | |
const keys = await caches.keys(); | |
return Promise.all( | |
keys.filter((key) => !CACHE_NAMES.includes(key)).map((key) => caches.delete(key)) | |
); | |
} | |
async function activateServiceWorker() { | |
await deleteOldCaches(); | |
await self.clients.claim(); | |
} | |
worker.addEventListener('install', (event) => { | |
event.waitUntil(cacheStaticAssets()); | |
}); | |
worker.addEventListener('activate', (event) => { | |
event.waitUntil(activateServiceWorker()); | |
}); | |
// Handle requests from the cache if available, otherwise fetch them | |
async function serve(request) { | |
const cache = await caches.open(APP_CACHE_NAME); | |
const cachedResponse = await cache.match(request); | |
if (cachedResponse) { | |
return cachedResponse; | |
} | |
try { | |
const networkResponse = await fetch(request); | |
// Cache successful network responses | |
if (networkResponse.ok) { | |
cache.put(request, networkResponse.clone()); | |
} | |
return networkResponse; | |
} catch (error) { | |
throw new Error(`Failed to fetch ${request.url}: ${error}`); | |
} | |
} | |
worker.addEventListener('fetch', (event) => { | |
const { request } = event; | |
if (request.method !== 'GET' || request.headers.has('range')) { | |
return; | |
} | |
const url = new URL(request.url); | |
// Don't handle data URIs | |
const isHttp = url.protocol.startsWith('http'); | |
const isDevServerRequest = | |
url.hostname === self.location.hostname && url.port !== self.location.port; | |
const skipUncachedRequests = request.cache === 'only-if-cached' && !isStaticAsset; | |
if (isHttp && !isDevServerRequest && !skipUncachedRequests) { | |
event.respondWith(serve(request)); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment