我是服务工作者和工作箱的新手。我目前正在使用工作箱来预先处理我的静态资产文件,这很好,我希望我的其他第三方URL在运行时也会被缓存,但是直到我第二次重新加载到页面上才能工作:(
下面显示的是我的服务工作者代码的副本,请注意我故意将我原来的链接替换为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字体和fontawesome中的资源无法在第一次缓存。下面是控制台和我的页面的缓存存储选项卡第一个加载图像和第二个加载图像。
请不要知道我做错了什么以及它为什么会这样。
提前致谢
这是预期的行为。
服务工作者设置的方式是他们将具有安装和激活阶段,其中安装可以在新服务工作者注册或服务工作者更新时发生。
然后,服务工作人员将在安全的情况下激活(即,当前没有窗口被“控制”为服务工作者)。
激活服务工作者后,它将控制任何新页面。
你看到的是:
服务工作者在激活之前不会缓存任何内容。它仅在第二次击中时激活。要在第一次访问时实现缓存,您必须指导服务工作者跳过等待激活。你可以做到这一点
self.addEventListener('install', () => {
self.skipWaiting(); //tells service worker to skip installing and activate it
/*your code for pre-caching*/
});
一旦被跳过它进入激活模式并等待缓存但它不会缓存客户端交互。为此,请应用以下行
self.addEventListener('activate', () => {
clients.claim();
});
它会在第一次打击时开始缓存