I am trying to implement an offline fallback functionality for pictures and documents that are not available in the cache. The idea is that when the desired pictures or documents are not available, the service worker would serve a predefined fallback picture or document. I am using the recipe described here but it is not working. To test it using the Chrome dev tools I do the following:
GET http://localhost:3003/assets/img/Innomaps%20en%20el%20Hult%20Prize%202019.jpg net::ERR_INTERNET_DISCONNECTEDservice worker code:
importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.1/workbox-sw.js');
workbox.core.setCacheNameDetails({
prefix: 'innomaps-pwa',
suffix: 'v1',
precache: 'precache-cache',
runtime: 'runtime-cache'
});
workbox.precaching.precacheAndRoute([
// Precaching the home page
{ url: '/', revision: null },
{ url: 'assets/css/styles.css', revision: null },
{ url: 'assets/js/actions.js', revision: null },
{ url: 'assets/img/InnomapsWhite.png', revision: null },
{ url: 'assets/js/bs-init.js', revision: null },
{ url: 'manifest.json', revision: null },
// Precaching the offline page
{ url: '/offline', revision: null },
]);
workbox.googleAnalytics.initialize();
// This feature is not working!!
workbox.recipes.offlineFallback({
pageFallback: '/offline',
imageFallback: 'assets/img/InnomapsWhite.png'
});
the '/' route is serving a simple HTML file.
The problem is that a route handler needs to be setup in order for the offline fallback recipe to catch it. If you are planning to use the offline fallback strategy for all non handled routes (as in my case) you can set up a default handler with your desired strategy (in the following case, the NetworkOnly strategy is used). The following code from @JeffPosnick in his response at my github issue works as a charm:
importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js');
workbox.routing.setDefaultHandler(
new workbox.strategies.NetworkOnly()
);
// Replace with your URLs.
workbox.recipes.offlineFallback({
pageFallback: '/offline.html',
imageFallback: '/offline.png'
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With