Skip to content

Instantly share code, notes, and snippets.

@charisTheo
Last active July 18, 2021 09:56
Show Gist options
  • Save charisTheo/717081fe8f6e560d15f73da68d51af79 to your computer and use it in GitHub Desktop.
Save charisTheo/717081fe8f6e560d15f73da68d51af79 to your computer and use it in GitHub Desktop.
When an image is not found either in the network (offline) or in the cache, respond with a precached placeholder image from the cache.
importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js');
const placeholderImageURL = '/img/placeholder-image.png'; // precache this in __WB_MANIFEST file
workbox.precaching.precacheAndRoute(self.__WB_MANIFEST || []);
workbox.routing.registerRoute(
/\.(?:webp|png|jpg|jpeg|svg)$/,
async ({url, event, params}) => {
const staleWhileRevalidate = new workbox.strategies.StaleWhileRevalidate();
try {
const response = await caches.match(event.request) || await fetch(url, { method: 'GET' });
if (!response || response.status === 404) {
throw new Error(response.status);
} else {
return await staleWhileRevalidate.handle({event});
}
} catch (error) {
console.warn(`\nServiceWorker: Image [${url.href}] was not found either in the network or the cache. Responding with placeholder image instead.\n`);
// * get placeholder image from cache || get placeholder image from network
return await caches.match(placeholderImageURL) || await fetch(placeholderImageURL, { method: 'GET' });
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment