如何缓存其他路由以供离线浏览?

fro*_*uma 6 offline-caching vue.js progressive-web-apps vue-router vue-cli-3

我正在设置一个支持离线浏览的渐进式 Web 应用程序。

我已经为我的主要路由 ('domainsample.com/') 设置了离线浏览,即使离线它也会响应 200。

但是当我导航到其他路由 ('domainsample.com/about') 时,我收到一个No Internet Page错误。

这是我在 Heroku 中部署的示例 URL:https : //pwa-hehe.herokuapp.com

我使用 Vue CLI 3 设置项目,使用 Node.js 和 Express.js 在服务器中运行我的 dist 文件夹。

// server.js
const express = require('express')
const path = require('path')
const history = require('connect-history-api-fallback')

const app = express()

const staticFileMiddleware = express.static(path.join(__dirname + '/dist'))

app.use(staticFileMiddleware)

app.use(history({
    disableDotRule: true,
    verbose: true
}))

app.use(staticFileMiddleware)

app.get('/', function (req, res) {
    res.render(path.join(__dirname + '/dist/'))
})

var server = app.listen(process.env.PORT || 3000, function () {
    var port = server.address().port
    console.log("App now running on port", port)
})
Run Code Online (Sandbox Code Playgroud)
// manifest.json
{
  "name": "pwa-offline",
  "short_name": "pwa-offline",
  "icons": [
    {
      "src": "./img/icons/android-chrome-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "./img/icons/android-chrome-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ],
  "start_url": "./index.html",
  "display": "standalone",
  "background_color": "#000000",
  "theme_color": "#4DBA87"
}

Run Code Online (Sandbox Code Playgroud)
// service-worker.js

/**
 * Welcome to your Workbox-powered service worker!
 *
 * You'll need to register this file in your web app and you should
 * disable HTTP caching for this file too.
 * 
 *
 * The rest of the code is auto-generated. Please don't update this file
 * directly; instead, make changes to your Workbox build configuration
 * and re-run your build process.
 * 
 */

importScripts("https://storage.googleapis.com/workbox-cdn/releases/3.6.3/workbox-sw.js");

importScripts(
  "/precache-manifest.d3f1ce5d8331bddc555348f44cfba9d8.js"
);

workbox.core.setCacheNameDetails({prefix: "pwa-offline"});

/**
 * The workboxSW.precacheAndRoute() method efficiently caches and responds to
 * requests for URLs in the manifest.
 * 
 */
self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.suppressWarnings();
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
Run Code Online (Sandbox Code Playgroud)

Fra*_*sco 0

问题是您的服务工作人员不知道要缓存哪些资产。的价值是什么self.__precacheManifest?(可能是网络清单文件)。

您需要配置工作箱以获得该precacheAndRoute方法的一些资源,因为这将指示服务工作线程缓存哪些文件以及何时缓存。就像是:

workbox.precaching.precacheAndRoute([
  '/styles/example.ac29.css',
  '/app/offlinePage.js',
  '/app/offlinePage.html',
  // ... other entries ...
]);
Run Code Online (Sandbox Code Playgroud)

默认情况下,Service Worker 不知道要缓存哪些资产或 HTTP 响应,因此我们必须根据我们的要求定义和实现缓存策略。

我写了一篇关于Service Worker 和可用缓存策略的文章。如果您想加深主题,请看一下。