重定向到离线页面

时间:2019-03-08 20:29:02

标签: javascript service-worker create-react-app workbox

我有一个使用React创建的create-react-app应用。默认情况下,该工具会为我们创建一个serviceWorker.js文件,我正在使用它来注册service-worker。此外,文档建议使用Google的workbox wizard创建service-worker.js来管理我的网站以供离线使用。我的目标是将offline.html页存储在浏览器缓存中,并且每当没有在线连接时,就渲染缓存的offline.html页。

我成功将offline.html存储在缓存中,如下所示。 enter image description here

但是,当没有连接时,我很难抓住这个文件并渲染它。这是我的代码:

workbox-config.js

module.exports = {
  "globDirectory": "build-development/",
  "globPatterns": [
    ".offline/*.html",
    "external/logo_purple.png"
  ],
  "swDest": "build-development/sw.js",
  "swSrc": "src/sw.js",
  "injectionPointRegexp": /(const precacheManifest = )\[\](;)/
};

sw.js (created by running the workbox config)

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

const precacheManifest = [];

workbox.precaching.precacheAndRoute(precacheManifest);

const dataCacheConfig = {
  cacheName: 'offline'
};

workbox.routing.registerRoute("http://localhost:4000/.offline/offline.html", workbox.strategies.cacheFirst(dataCacheConfig), 'GET');

有什么想法吗?

0 个答案:

没有答案