Cache specific URLs
See original GitHub issueHello! I am addressing a special case which is as follows:
The site has around 42k+ pages and are frequently updated. I am looking for a way to convert this site into PWA such that only the Home page (https://www.example.com/) and its assets are cached as staleWhileRevalidate
. The rest of the pages (any occurrences of a pathname ) are served as networkOnly
, and hence when the user is offline, they are shown an offline.html
page.
I have checked the documentation and the closest I have come across is this Offline page only recipe where the offline page is served while offline.
const {registerRoute, NavigationRoute} = workbox.routing;
const {NetworkOnly} = workbox.strategies;
const { navigationPreload } = workbox;
const CACHE_NAME = 'offline-html';
// This assumes /offline.html is a URL for your self-contained
// (no external images or styles) offline page.
const FALLBACK_HTML_URL = '/offline.html';
// Populate the cache with the home page and offline HTML page when the
// service worker is installed.
self.addEventListener('install', async (event) => {
event.waitUntil(
caches.open(CACHE_NAME)
.then((cache) => cache.addAll(['/offline.html', '/index.html']))
);
});
navigationPreload.enable();
const networkOnly = new NetworkOnly();
const navigationHandler = async (params) => {
try {
// Attempt a network request.
return await networkOnly.handle(params);
} catch (error) {
// If it fails, return the cached HTML.
return caches.match(FALLBACK_HTML_URL, {
cacheName: CACHE_NAME,
});
}
};
// Register this strategy to handle all navigations.
registerRoute(
new NavigationRoute(navigationHandler)
);
I’m trying to extend this code to make an exception for the home page URL to be cached along with the offline page but haven’t got any luck yet. The index.html
is in cache but couldn’t get away to add an exception with a StaleWhileRevalidate
method.
Any pointers would be highly appreciated.
Issue Analytics
- State:
- Created 2 years ago
- Comments:7 (4 by maintainers)
Top GitHub Comments
setDefaultHandler()
registers a handler that will be used by default when there is no matching route, so it doesn’t support passing in amatchCallback
. Think of it as a last-chance fallback strategy for anything that isn’t matched via one of yourregisterRoute()
s.It sounds like you want to add in one or more additional calls to
registerRoute()
with the a combination of match criteria and strategy. If all of your requests are explicitly handled by a registered route, you could remove thesetDefaultHandler()
entirely. I just added it in because it sounded like it would work based on your initial description.In any case, I’m glad that you have something that should work for you!
How about this?