簡體   English   中英

Workbox Service Worker 無法正常使用 PWA

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

我正在嘗試使用 Workbox 與服務人員一起制作一個非常基本的 PWA,但我遇到了問題。 我正在使用命令行界面生成服務工作者,一切正常,完美的 lightscore 但我無法將我的 index.html 添加到運行時緩存中。 我必須將它添加到全局模式中,以便我的網站在離線模式下工作,但是當我更新我的 index.html 文件時,除非我清除緩存,否則它不會更新。 我想要和我的 js 和 css 一樣的東西。 當我升級這些文件時,它們會更新。 這是我的工作箱配置文件:

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",
      },
    },
  ],
};

我對您的問題的解釋是您不想使用預緩存,因為您不希望緩存優先 HTML。 如果是這樣,那很好——在這種情況下,您實際上不需要使用workbox-cli

相反,如果您只是使用運行時緩存,則可以完全避免使用 Workbox 構建工具,而只需部署一個安裝默認NetworkFirst路由的服務工作線程文件:

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();

一旦注冊了該服務工作者,所有響應將在運行時自動緩存,並且如果您曾經離線,則先前緩存的響應將用作后備(假設先前的請求已填充緩存)。

如果需要,您可以將其與調用 `workbox.recipes.warmStrategyCache

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM