navigation preload workbox code example
Example 1: navigation Preload example workbox
addEventListener("fetch", event =>
event.request.mode === "navigate" &&
new URL(event.request.url, location.origin).pathname !== "/test" &&
event.respondWith(event.preloadResponse)
);
Example 2: navigation Preload example workbox
// these are the routes we want to cache (i.e. no navigation preload will be necessary for these)
const routes = getRoutes(shells, paths);
// we enable
navigationPreload.enable();
// we set up a navigation route catching all paths apart from the routes we are caching
const navigationRoute = new routing.NavigationRoute(new strategies.NetworkOnly(), {
blacklist: routes.map(route => {
return new RegExp(`/${language}-${country}/${route.path}`);
})
});
routing.registerRoute(navigationRoute);
// we register the routes we want to cache using StaleWhileRevalidate strategy
for (let i = 0; i < routes.length; i++) {
const staleWhileRevalidate = new strategies.StaleWhileRevalidate({ cacheName: routes[i].id });
const shellRegEx = `/${language}-${country}/${routes[i].shell}`;
const pathRegEx = new RegExp(`/${language}-${country}/${routes[i].path}`);
routing.registerRoute(pathRegEx, () => {
return staleWhileRevalidate.handle({ request: shellRegEx });
});
}
// this is where we tried following the advice from @astrinxit66 i.e. we'll handle the preload response for these whitelisted navigation routes by using a CacheFirst strategy (since we cache these using the StaleWhileRevalidate strategy above)
const navigationRouteForShells = new routing.NavigationRoute(new strategies.CacheFirst(), {
whitelist: routes.map(route => {
return new RegExp(`/${language}-${country}/${route.path}`);
})
});
routing.registerRoute(navigationRouteForShells);