我用 npx create-nuxt-app
创建了我的应用程序,然后添加 npm install @nuxtjs/pwa --save
.我在 index.html 中包含了一个谷歌字体:
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons" rel="stylesheet" data-n-head="true">
我通过单击开发工具/应用程序选项卡中的“离线”复选框并重新加载,在 Chrome 中以离线模式测试了我的应用程序。除了字体,所有东西都被缓存了。
我接着补充说:
workbox: {
runtimeCaching: [
{
urlPattern: 'https://fonts.googleapis.com/.*',
handler: 'cacheFirst',
method: 'GET'
},
]
}
到
nuxt.config.js
文件,但我无法缓存字体。我在 urlPattern 上尝试了许多变体。Nuxt 正在为我生成一个 service worker,它看起来像这样:
importScripts('/_nuxt/workbox.3de3418b.js')
const workboxSW = new self.WorkboxSW({
"cacheId": "my-app",
"clientsClaim": true,
"directoryIndex": "/"
})
workboxSW.precache([
{
"url": "/_nuxt/app.bb74329360a7ee70c2af.js",
"revision": "8477c51cbf9d3188f34f1d61ec1ae6bc"
},
{
"url": "/_nuxt/layouts/default.ce9446c7c3fffa50cfd2.js",
"revision": "504d33b2d46614e60d919e01ec59bbc8"
},
{
"url": "/_nuxt/manifest.912c22076a54259e047d.js",
"revision": "a51a74b56987961c8d34afdcf4efa85c"
},
{
"url": "/_nuxt/pages/index.6bfd6741c6dfd79fd94d.js",
"revision": "1a80379a5d35d5d4084d4c2b85e1ee10"
},
{
"url": "/_nuxt/vendor.f681eb653617896fcd64.js",
"revision": "59c58901fd5142fdaac57cbee8c1aeb4"
}
])
workboxSW.router.registerRoute(new RegExp('/_nuxt/.*'), workboxSW.strategies.cacheFirst({}), 'GET')
workboxSW.router.registerRoute(new RegExp('/.*'), workboxSW.strategies.networkFirst({}), 'GET')
workboxSW.router.registerRoute(new RegExp('https://fonts.googleapis.com/.*'), workboxSW.strategies.cacheFirst({}), 'GET')
为什么字体没有被缓存?
编辑#1:
感谢 Jeff Posnick,我明白发生了什么。我还没有想出正确的语法来传递
nuxt.config.js
文件,但作为一个实验,我黑了 sw.js
直接文件并添加这两行:workboxSW.router.registerRoute(new RegExp('https://fonts.googleapis.com/.*'),
workboxSW.strategies.cacheFirst({cacheableResponse: {statuses: [0, 200]}}),
'GET')
workboxSW.router.registerRoute(new RegExp('https://fonts.gstatic.com/.*'),
workboxSW.strategies.cacheFirst({cacheableResponse: {statuses: [0, 200]}}),
'GET')
那行得通!
最佳答案
对于 workbox 的第 2 版和@nuxt/pwa 的第 2 版,这是 nuxt.config.js
中所需的语法。文件:
workbox: {
runtimeCaching: [
{
urlPattern: 'https://fonts.googleapis.com/.*',
handler: 'cacheFirst',
method: 'GET',
strategyOptions: {cacheableResponse: {statuses: [0, 200]}}
},
{
urlPattern: 'https://fonts.gstatic.com/.*',
handler: 'cacheFirst',
method: 'GET',
strategyOptions: {cacheableResponse: {statuses: [0, 200]}}
},
]
}
关于service-worker - 使用 nuxt 和 @nuxtjs/pwa 的网站不缓存谷歌字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49117416/