Last active
July 18, 2021 09:56
-
-
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.
This file contains hidden or 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
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