Skip to content

Instantly share code, notes, and snippets.

@YonatanKra
Created June 19, 2023 13:15
Show Gist options
  • Save YonatanKra/26019e8fbf312d89abfe07b9d2bfc857 to your computer and use it in GitHub Desktop.
Save YonatanKra/26019e8fbf312d89abfe07b9d2bfc857 to your computer and use it in GitHub Desktop.
Service Worker for caching our files
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