添加Workbox脱机支持和html缓存

问题描述 投票:0回答:1

我正在尝试从工作箱开始。我想将我的网站编码为PWA。它应该脱机工作。为此,我想使用CacheFirst策略。我的问题是,该工作箱无法离线工作。而且我什至在缓存中找不到我的主要html文件。这是我在主要html文件中对ServiceWorker的初始化:

<script>
    if ('serviceWorker' in navigator) {
      window.addEventListener('load', () => {
        navigator.serviceWorker.register('./service-worker.js');
      });
    }
  </script>  

这是我的service-worker.js文件:

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

workbox.routing.registerRoute(
  /\.html/,
  new workbox.strategies.CacheFirst({
    cacheName: 'html-cache',
  })
);

workbox.routing.registerRoute(
  /\.css$/,
  new workbox.strategies.CacheFirst({
    cacheName: 'css-cache',
  })
);

workbox.routing.registerRoute(
  /\.js/,
  new workbox.strategies.CacheFirst({
    cacheName: 'js-cache',
  })
);

workbox.routing.registerRoute(
  /\.(?:png|jpg|jpeg|svg|gif)$/,
  new workbox.strategies.CacheFirst({
    cacheName: 'image-cache',
    plugins: [
      new workbox.expiration.Plugin({
        maxEntries: 20,
        maxAgeSeconds: 7 * 24 * 60 * 60,
      })
    ],
  })
);

您会看到我已对其进行初始化并根据需要进行设置。 Here you can see the caches in the dev console.但是您可以看到没有html缓存。为什么?再次,它不能离线工作。附加信息:由于服务工作者需要,因此我正在通过HTTPS运行网站。希望有人能帮助我。〜马库斯

javascript html service-worker workbox
1个回答
0
投票

HTML不会被缓存,因为很可能是在没有.html扩展名的情况下加载或链接HTML的,就像这样:

https://example.com/

<a href="/about">About</a>

但是,用于将请求匹配到HTML页面的RegExp检查.html扩展名:

workbox.routing.registerRoute(
  /\.html/,
  ...
);

CSS,JS和图像资源得到了正确的缓存,因为它们很可能正在以其文件扩展名加载,这些文件扩展名与传递给Workbox的RegExp模式匹配。

要解决此问题,请确保用于请求HTML页面的URL与该模式匹配。实现此目的的一种方法是访问它们或使用.html扩展名链接到它们:

https://example.com/index.html
https://example.com/about.html

<a href="/about.html">About</a>

在大多数情况下,最好使用不带.html扩展名的URL。在这种情况下,仍要缓存HTML页面,可以使用其他匹配URL的方法。 Workbox支持多种路由请求的方法:使用字符串,RegExp或回调函数。 documentation很好地说明了何时使用每一个。一种看起来可能是这样的方式(可以根据需要简单或复杂):

function matchFunction({ url }) {
  const pages = ['/', '/about'];
  return pages.includes(url.pathname);
}

workbox.routing.registerRoute(
  matchFunction,
  new workbox.strategies.CacheFirst({
    cacheName: 'html-cache'
  })
);
© www.soinside.com 2019 - 2024. All rights reserved.