简体   繁体   中英

Workbox service worker doesn't work as it should with PWA

I'm trying to make a very basic PWA with a service worker using Workbox but I have a problem. I'm using the command line interface to generate the service worker, everything works, perfect lightscore but I can't add my index.html to the runtime caching. I have to add it to the global patterns so that my website works in offline mode but then when I update my index.html file it doesn't get updated unless I clear my cache. I want the same thing as my js and css. When I upgrade those files they get updated. Here is my workbox configuration file:

module.exports = {
  globDirectory: "./",
  globPatterns: ["**/*.{html,json}"],
  swDest: "./serviceworker.js",
  // Define runtime caching rules.
  runtimeCaching: [
    {
      // Match any request that ends with .png, .jpg, .jpeg or .svg.  urlPattern: /\.(?:png|jpg|jpeg|svg)$/,
      urlPattern: /\.(?:png|jpg|jpeg|svg)$/,
      // Apply a network-first strategy.
      handler: "NetworkFirst",
      options: {
        // Use a custom cache name.
        cacheName: "images",
      },
    },
    {
      urlPattern: /\.(?:js|css)$/,
      handler: "NetworkFirst",
      options: {
        cacheName: "main",
      },
    },
  ],
};

My interpretation of your question is that you don't want to use precaching, because you would prefer not to have cache-first HTML. If so, that's fine—you don't actually need to use workbox-cli in that case.

Instead, if you're just using runtime caching, you could avoid using Workbox build tools entirely, and instead just deploy a service worker file that installs a default NetworkFirst route:

importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.1/workbox-sw.js');

const strategy = new workbox.strategies.NetworkFirst();
workbox.routing.setDefaultHandler(strategy);

// Ensure that our cache is pre-populated at install time,
// which will help with offline checks.
const urls = [
  '/',
  // Add any other URLs that you want to ensure are cached here.
];
workbox.recipes.warmStrategyCache({urls, strategy});

workbox.core.clientsClaim();

Once that service worker is registered, all responses will automatically be cached at runtime, and if you're ever offline, the previously cached response will be used as a fallback (assuming there was a previous request that had populated the cache).

If you want, you can mix this with a call to `workbox.recipes.warmStrategyCache

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM