我正试着从workbox开始。我想把我的网站编码为PWA。它应该离线工作。为此,我想使用CacheFirst策略。我的问题是,workbox不能脱机工作。我甚至在缓存中找不到我的主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-cache。为什么?同样,它也不能离线工作。附加信息:我正在运行HTTPS的网站,因为它是服务人员所需要的。希望有人能帮我。
~马库斯
发布于 2020-01-07 19:55:18
超文本标记语言不会缓存,因为它们很可能是在没有.html扩展的情况下加载或链接的,如下所示:
https://example.com/
<a href="/about">About</a>但是,用于将请求与HTML页匹配的RegExp检查.html扩展名:
workbox.routing.registerRoute(
/\.html/,
...
);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'
})
);https://stackoverflow.com/questions/59611238
复制相似问题