我用npx create-nuxt-app
创建了我的应用,然后添加了npm install @nuxtjs/pwa --save
。我在index.html中加入了Google字体,其中包括:
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons" rel="stylesheet" data-n-head="true">
我通过在devtools /应用程序标签中点击“离线”复选框并重新加载,在Chrome中以离线模式测试了我的应用程序。除字体外,所有内容均被缓存。
然后添加:
workbox: {
runtimeCaching: [
{
urlPattern: 'https://fonts.googleapis.com/.*',
handler: 'cacheFirst',
method: 'GET'
},
]
}
到nuxt.config.js
文件,但无法获取要缓存的字体。我在urlPattern上尝试了多种变体。
Nuxt正在为我生成服务工作者,它看起来像这样:
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')
有效!
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]}}
},
]
}
cacheFirst
策略来缓存不透明的响应,除非您明确告知。这是与Workbox v2混淆的常见原因,并且我们为即将发布的v3版本改进了JavaScript控制台日志和文档。 “ Handle Third Party Requests”指南会更详细。
您可以将配置更改为
runtimeCaching: [{
urlPattern: 'https://fonts.googleapis.com/.*',
handler: 'cacheFirst',
method: 'GET',
cacheableResponse: {statuses: [0, 200]}
}]
要在当前版本的Workbox中获得该行为。
@nuxtjs/[email protected]
和[email protected]
测试。C0]中下面的[pwa
属性按预期方式创建了新的缓存:
nuxt.config.js
可以在Chrome DevTools的[应用程序]选项卡的 pwa: {
workbox: {
runtimeCaching: [
{
urlPattern: 'https://my-api-url/.*',
handler: 'networkFirst',
method: 'GET',
strategyOptions: {
cacheName: 'my-api-cache',
cacheableResponse: {statuses: [0, 200]}
}
}
]
}
},
部分中确认缓存内容。