caching - 工作箱软件 : Runtime caching not working until second Reload

标签 caching progressive-web-apps workbox

我是服务 worker 和工作箱的新手。我目前正在使用工作箱来预缓存我的静态 Assets 文件,它工作正常,我希望我的其他第三方 URL 在运行时也能被缓存,但直到我在页面上第二次重新加载时才工作:(

下面显示的是我的 Service Worker 代码的副本,请注意我故意替换了我原来的 abc.domain.com 链接:)

workbox.routing.registerRoute(
  //get resources from any abc.domain.com/
  new RegExp('^https://abc.(?:domain).com/(.*)'),
  /*
  *respond with a cached response if available, falling back to the network request if it’s not cached. 
  *The network request is then used to update the cache.
  */
  workbox.strategies.staleWhileRevalidate({
    cacheName: 'Bill Resources',
    maxEntries: 60,
    maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
  }),
); 

workbox.routing.registerRoute(
  new RegExp('^https://fonts.(?:googleapis|gstatic).com/(.*)'),
  //serve from network first, if not availabe then cache
  workbox.strategies.networkFirst(),
); 

workbox.routing.registerRoute(
  new RegExp('^https://use.(?:fontawesome).com/(.*)'),
  //serve from network first, if not availabe then cache
  workbox.strategies.networkFirst(),
); 

我清除了没有数字的存储时间,我从谷歌开发者工具刷新了缓存存储,但似乎都是一样的。来自自定义链接的资源,google fonts 和 fontawesome,第一次缓存失败。下面分别是我的页面第一个加载图像和第二个加载图像的控制台和缓存存储选项卡。

First Load
Second Load

请我不知道我做错了什么以及为什么它会这样。

提前致谢

最佳答案

这是预期的行为。

Service Worker 的设置方式是,他们将有一个安装和激活阶段,当新的 Service Worker 注册或 Service Worker 更新时,就会进行安装。

Service Worker 将在安全的情况下激活(即当前没有窗口被“控制”为 Service Worker)。

一旦 Service Worker 被激活,它将控制任何新页面。

你看到的是:

  • 页面已加载,页面注册了 service worker
  • Service Worker 在安装阶段预缓存所有文件
  • 服务激活但不控制任何页面
  • 你刷新页面,此时页面被控制,请求将通过服务 worker (导致第二次加载时的缓存)。
  • 关于caching - 工作箱软件 : Runtime caching not working until second Reload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49897182/

    相关文章:

    caching - Cache-Control 的无缓存和必须重新验证之间的区别?

    caching - 可编程CPU缓存?

    html 5 appcache 用户控制更新

    iphone - UIWebView加载本 map 片的时滞

    javascript - Web worker importScripts DOMException 脚本加载失败

    ios - 将 iOS 推送通知链接到 PWA/网站

    reactjs - React 和 Serviceworker (Workbox)

    mobile-safari - PWA-缓存的视频将无法在Mobile Safari(11.4)中播放

    javascript - Workbox - 使用自定义处理程序

    Chrome 中 Service-Worker 处于等待状态