Created
June 19, 2023 13:15
-
-
Save YonatanKra/26019e8fbf312d89abfe07b9d2bfc857 to your computer and use it in GitHub Desktop.
Service Worker for caching our files
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
const addResourcesToCache = async (resources) => { | |
const cache = await caches.open('vivid-cache'); | |
await cache.addAll(resources); | |
}; | |
const putInCache = async (request, response) => { | |
const cache = await caches.open('vivid-cache'); | |
await cache.put(request, response); | |
}; | |
const cacheFirst = async ({ request, preloadResponsePromise, fallbackUrl }) => { | |
const responseFromCache = await caches.match(request); | |
if (responseFromCache) { | |
return responseFromCache; | |
} | |
const preloadResponse = await preloadResponsePromise; | |
if (preloadResponse) { | |
console.info('using preload response', preloadResponse); | |
await putInCache(request, preloadResponse.clone()); | |
return preloadResponse; | |
} | |
try { | |
const responseFromNetwork = await fetch(request); | |
await putInCache(request, responseFromNetwork.clone()); | |
return responseFromNetwork; | |
} catch (error) { | |
const fallbackResponse = await caches.match(fallbackUrl); | |
if (fallbackResponse) { | |
return fallbackResponse; | |
} | |
return new Response('Network error happened', { | |
status: 408, | |
headers: { 'Content-Type': 'text/plain' }, | |
}); | |
} | |
}; | |
const enableNavigationPreload = async () => { | |
if (self.registration.navigationPreload) { | |
await self.registration.navigationPreload.enable(); | |
} | |
}; | |
self.addEventListener('activate', (event) => { | |
event.waitUntil(enableNavigationPreload()); | |
}); | |
self.addEventListener('install', (event) => { | |
event.waitUntil( | |
addResourcesToCache([ | |
'./', | |
'./index.html', | |
'/assets/styles/core/all.css', | |
'/assets/scripts/vivid-components.js', | |
'/assets/scripts/live-sample.js', | |
]) | |
); | |
}); | |
self.addEventListener('fetch', (event) => { | |
event.respondWith( | |
cacheFirst({ | |
request: event.request, | |
preloadResponsePromise: event.preloadResponse, | |
fallbackUrl: './assets/images/vivid-logo.jpeg', | |
}) | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment