Skip to content
Search

Workbox:Strategies

lastmod 2023-03-15created 2023-03-153 edits

Stale-while-revalidate example

workbox.routing.registerRoute(
  /\.(?:js|css|webp|png|svg)$/,
  new workbox.strategies.StaleWhileRevalidate()
);

Network First

workbox.routing.registerRoute(
  /(\/|\.html)$/,
  new workbox.strategies.NetworkFirst()
);

How to handle index.html caching in create-react-app

If you used create-react-app with cra-template-pwa (npx create-react-app my-app --template cra-template-pwa), you can filter out index.html when registering the index after precaching. Change it to be network-first:

import { NetworkFirst } from 'workbox-strategies'

// precacheAndRoute(self.__WB_MANIFEST)

const toPrecache = self.__WB_MANIFEST.filter(
  (file) => !file.url.includes('index.html'),
)

precacheAndRoute(toPrecache)

registerRoute(
  ({ url }) => url.pathname.includes('index.html'),
  new NetworkFirst(),
)

Then you need to remove the part that routes all navigation requests to index.html.

// Set up App Shell-style routing, so that all navigation requests
// are fulfilled with your index.html shell. Learn more at
// https://developers.google.com/web/fundamentals/architecture/app-shell
// const fileExtensionRegexp = new RegExp('/[^/?]+\\.[^/]+$')
// registerRoute(
//   // Return false to exempt requests from being fulfilled by index.html.
//   ({ request, url }) => {
//     // If this isn't a navigation, skip.
//     if (request.mode !== 'navigate') {
//       return false
//     } // If this is a URL that starts with /_, skip.

//     if (url.pathname.startsWith('/_')) {
//       return false
//     } // If this looks like a URL for a resource, because it contains // a file extension, skip.

//     if (url.pathname.match(fileExtensionRegexp)) {
//       return false
//     } // Return true to signal that we want to use the handler.

//     return true
//   },
//   createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html', true),
// )

See also

Favorite site

author Zer0 sitemap