使用Nuxt与@nuxtjs/pwa时Google Fonts无法缓存的问题求助
我来帮你搞定这个Nuxt PWA离线模式下Google Fonts没被缓存的问题——之前我自己做项目时也踩过这个坑,咱们一步步调整就能解决:
1. 自定义Workbox缓存规则(核心步骤)
Nuxt的PWA模块默认的Workbox配置不会自动包含Google Fonts的域名,所以需要在nuxt.config.js里手动添加runtimeCaching规则,分别处理字体样式表和字体文件:
export default { // 其他Nuxt配置... pwa: { workbox: { runtimeCaching: [ // 缓存Google Fonts的样式表 { urlPattern: 'https://fonts.googleapis.com/.*', handler: 'StaleWhileRevalidate', // 优先用缓存,后台更新 method: 'GET', strategyOptions: { cacheName: 'google-fonts-stylesheets', cacheableResponse: { statuses: [0, 200] // 处理跨域的0状态码 } } }, // 缓存Google Fonts的字体文件 { urlPattern: 'https://fonts.gstatic.com/.*', handler: 'CacheFirst', // 优先用缓存,适合静态资源 method: 'GET', strategyOptions: { cacheName: 'google-fonts-webfonts', cacheableResponse: { statuses: [0, 200] }, expiration: { maxEntries: 30, // 最多缓存30个字体文件 maxAgeSeconds: 30 * 24 * 60 * 60 // 缓存30天 } } } ] } } }
这里要注意:样式表用StaleWhileRevalidate是因为Google可能会更新字体的CSS定义;字体文件用CacheFirst更高效,因为字体资源很少变动,加上过期策略可以避免缓存冗余。
2. 检查Google Fonts的引入方式
确保你在index.html里是用<link>标签引入字体,而不是@import:
<!-- 正确的引入方式 --> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap">
@import的资源不会被Service Worker自动拦截缓存,所以一定要用<link>标签。
3. 清理旧缓存与Service Worker
旧的Service Worker或缓存可能会干扰新配置的生效,按以下步骤清理:
- 打开Chrome开发者工具 → 切换到
Application面板 - 在
Service Workers选项里,点击Unregister删除旧的Service Worker - 再到
Cache Storage里,删除所有和你的项目相关的缓存项 - 重启Nuxt开发服务(
npm run dev重启),重新加载页面
4. 验证缓存效果
在线模式下刷新页面后,回到Application→Cache Storage,你应该能看到google-fonts-stylesheets和google-fonts-webfonts两个缓存项,里面包含对应的字体资源。这时候再勾选Offline选项刷新页面,字体就能正常加载了。
内容的提问来源于stack exchange,提问作者Paulie
相关产品推荐
相关产品推荐

