question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Cache specific URLs

See original GitHub issue

Hello! 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.
image

Any pointers would be highly appreciated.

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:7 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
jeffposnickcommented, Aug 13, 2021

setDefaultHandler() registers a handler that will be used by default when there is no matching route, so it doesn’t support passing in a matchCallback. Think of it as a last-chance fallback strategy for anything that isn’t matched via one of your registerRoute()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 the setDefaultHandler() 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!

1reaction
jeffposnickcommented, Aug 9, 2021

How about this?

const {registerRoute, setDefaultHandler} = workbox.routing;
const {NetworkOnly, StaleWhileRevalidate} = workbox.strategies;
const {navigationPreload} = workbox;

// I think you ca just cache the offline content ahead of time.
// The runtime s-w-r strategy should take care getting / in the cache.
const CACHE_NAME = 'offline-html';
const FALLBACK_HTML_URL = '/offline.html';
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then((cache) => cache.add(FALLBACK_HTML_URL))
  );
});

// Enable navigation preload.
navigationPreload.enable();

// Register a NetworkOnly route, which will take advanage of navigation preload
// whenever it's a navigation request for any URL other than /
// (You can add a check for `/index.html` if you also want to exclude that.)
registerRoute(
  ({request, url}) => request.mode === 'navigate' && url.pathname !== '/',
  new NetworkOnly({
    plugins: [{
      // See https://developers.google.com/web/tools/workbox/guides/using-plugins
      handlerDidError: () => caches.match(FALLBACK_HTML_URL),
    }],
  })
);

// Optional: you didn't mention it, but you might want an additional route here
// to cache large assets, like images, with a policy other than the default one.

// For all other requests, i.e. assets/subresources or navigations to /,
// use StaleWhileRevalidate.
setDefaultHandler(new StaleWhileRevalidate());
Read more comments on GitHub >

github_iconTop Results From Across the Web

How can I cache specific urls? - Laracasts
I have an image url defined in web.php as Route::get('/images/{path}/{number?}', 'PagesController@image')->name('images'); But since the images aren't ...
Read more >
How do I include or exclude a specific URL from Cloudflare's ...
You can exclude certain URLs from Cloudflare's caching by using the Page Rules in the Cloudflare dashboard to set Cache Level to Bypass....
Read more >
How to clear the browser's Cache for a specific URL / page
1. Open the Developer Tools panel, if you want a shortcut it is: Press SHIFT+CTRL+I or right click on a blank area and...
Read more >
Cache for only specific URLs with retrofit - java - Stack Overflow
I need to cache response of only specific url addresses in my app; but what I found with many searches that I've done...
Read more >
Bypassing the cache for specific URL patterns
How to bypass the cache for specific URLs and URL patterns in Varnish. ... Bypassing the cache in Varnish is done by calling...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found