I am trying to set up a simple Service Worker for a small static site, moving it from v3 Workbox to v5.
Precache 404.html and offline.html. Cache *.html files for just 5 mins, cache all other files for 30 days handle 404 and offline status with an offline page.
It works offline with already cached pages and shows these. However, visiting new pages does not take me to the offline page as expected. Help from Workbox 5 syntax error - Uncaught TypeError: workbox.expiration.CacheableResponsePlugin is not a constructor got me past one error.
The console error is "Uncaught (in promise) no-response: no-response."
User gets "This site cannot be reached. The webpage at ... might be temporarily down or may have moved to a new web address ERR_FAILED
Any suggestions on how to fix this would be appreciated.
/**
* Welcome to your Workbox-powered service worker!
*
* You'll need to register this file in your web app and you should
* disable HTTP caching for this file too.
*
*
* The rest of the code is auto-generated. Please don't update this file
* directly; instead, make changes to your Workbox build configuration
* and re-run your build process.
*
*/
importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.1.4/workbox-sw.js')
if (workbox) {
console.log('Yay! Workbox is loaded');
/**
* The workboxSW.precacheAndRoute() method efficiently caches and responds to
* requests for URLs in the manifest.
*
*/
/* https://developers.google.com/web/tools/workbox/modules/workbox-sw -namespace */
/* https://developers.google.com/web/tools/workbox/guides/precache-files */
workbox.precaching.precacheAndRoute(
[
{ url: "404.html", revision: "ca66a569ea978f2cca26acf6994d7e49" },
{ url: "offline.html", revision: "112452c5d7bf793db0ab9a37cf30d178" }
]
);
workbox.routing.registerRoute(
/\.(?:png|gif|jpg|svg|css|js|json)$/,
new workbox.strategies.CacheFirst({
cacheName: 'nonhtml-cache',
plugins: [
new workbox.expiration.ExpirationPlugin({
maxEntries: 50,
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
})
]
})
)
workbox.routing.registerRoute(
/\.(?:html)$/,
new workbox.strategies.NetworkFirst({
cacheName: 'html-cache',
plugins: [
new workbox.cacheableResponse.CacheableResponsePlugin({
statuses: [0, 200, 206],
}),
new workbox.expiration.ExpirationPlugin({
maxEntries: 50,
maxAgeSeconds: 5 * 60,
})
]
})
)
//changes replace /404 with 404, replace php$ with php
workbox.routing.registerRoute(/\.html/, args => {
return articleHandler.handle(args).then(response => {
if (!response) {
return caches.match('offline.html');
} else if (response.status === 404) {
return caches.match('404.html');
}
return response;
});
});
} else {
console.log('Boo! Workbox did not load');
}