创建离线后备网页

Google 助理应用、Slack 应用、Zoom 应用,以及手机或计算机上的几乎任何其他平台专用应用有什么共同点?没错,它们始终至少会给您提供一些东西。 即使没有网络连接,您仍然可以打开 Google 助理应用、输入 Slack 或启动 Zoom。您可能无法获得任何特别有意义的东西,甚至无法实现您想要实现的目标,但至少可以实现目标,并且应用处于控制之中。

离线时的 Google 助理移动应用。
Google 助理。

离线时的 Slack 移动应用。
Slack。

离线时 Zoom 移动应用。
缩放。

借助平台专用应用,即使您没有网络连接,也永远无法获取任何内容。

相比之下,在浏览网络时,传统上当您处于离线状态时什么都不会获得。Chrome 为您提供了离线恐龙游戏,一切就是这样。

Google Chrome 移动应用,显示了离线恐龙游戏。
Google Chrome(iOS 版)。

Google Chrome 桌面应用,显示了离线恐龙游戏。
适用于 macOS 的 Google Chrome。

在网页上,如果您没有网络连接,默认情况下不会显示任何内容。

带有自定义 Service Worker 的离线回退网页

不过,情况并非必然如此。借助 Service Worker 和 Cache Storage API,您可为用户提供定制的离线体验。这可以是包含用户当前离线信息的简单品牌网页,也可以是更具创造性的解决方案,例如,著名的 trivago 离线迷宫游戏包含手动重新连接按钮和自动重新连接尝试倒计时。

包含 trivago 离线迷宫的 trivago 离线网页。
trivago 离线迷宫。

注册 Service Worker

可通过 Service Worker 做到这一点。您可以从主页面注册 Service Worker,如以下代码示例所示。通常,您应在应用加载后执行此操作。

window.addEventListener("load", () => {
  if ("serviceWorker" in navigator) {
    navigator.serviceWorker.register("service-worker.js");
  }
});

Service Worker 代码

乍一看,实际 Service Worker 文件的内容可能有点复杂,但以下示例中的注释应该能说明问题。核心思路是预缓存一个名为 offline.html 的文件,该文件仅在导航请求失败时提供,并让浏览器处理所有其他情况:

/*
Copyright 2015, 2019, 2020, 2021 Google LLC. All Rights Reserved.
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 http://www.apache.org/licenses/LICENSE-2.0
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

// Incrementing OFFLINE_VERSION will kick off the install event and force
// previously cached resources to be updated from the network.
// This variable is intentionally declared and unused.
// Add a comment for your linter if you want:
// eslint-disable-next-line no-unused-vars
const OFFLINE_VERSION = 1;
const CACHE_NAME = "offline";
// Customize this with a different URL if needed.
const OFFLINE_URL = "offline.html";

self.addEventListener("install", (event) => {
  event.waitUntil(
    (async () => {
      const cache = await caches.open(CACHE_NAME);
      // Setting {cache: 'reload'} in the new request ensures that the
      // response isn't fulfilled from the HTTP cache; i.e., it will be
      // from the network.
      await cache.add(new Request(OFFLINE_URL, { cache: "reload" }));
    })()
  );
  // Force the waiting service worker to become the active service worker.
  self.skipWaiting();
});

self.addEventListener("activate", (event) => {
  event.waitUntil(
    (async () => {
      // Enable navigation preload if it's supported.
      // See https://developers.google.com/web/updates/2017/02/navigation-preload
      if ("navigationPreload" in self.registration) {
        await self.registration.navigationPreload.enable();
      }
    })()
  );

  // Tell the active service worker to take control of the page immediately.
  self.clients.claim();
});

self.addEventListener("fetch", (event) => {
  // Only call event.respondWith() if this is a navigation request
  // for an HTML page.
  if (event.request.mode === "navigate") {
    event.respondWith(
      (async () => {
        try {
          // First, try to use the navigation preload response if it's
          // supported.
          const preloadResponse = await event.preloadResponse;
          if (preloadResponse) {
            return preloadResponse;
          }

          // Always try the network first.
          const networkResponse = await fetch(event.request);
          return networkResponse;
        } catch (error) {
          // catch is only triggered if an exception is thrown, which is
          // likely due to a network error.
          // If fetch() returns a valid HTTP response with a response code in
          // the 4xx or 5xx range, the catch() will NOT be called.
          console.log("Fetch failed; returning offline page instead.", error);

          const cache = await caches.open(CACHE_NAME);
          const cachedResponse = await cache.match(OFFLINE_URL);
          return cachedResponse;
        }
      })()
    );
  }

  // If our if() condition is false, then this fetch handler won't
  // intercept the request. If there are any other fetch handlers
  // registered, they will get a chance to call event.respondWith().
  // If no fetch handlers call event.respondWith(), the request
  // will be handled by the browser as if there were no service
  // worker involvement.
});

离线后备网页

offline.html 文件中,您可以发挥创意,根据需要做出调整,并添加品牌信息。以下示例展示了最低限度所允许的情况。 它演示了基于按钮的手动重新加载,以及基于 online 事件和常规服务器轮询的自动重新加载。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <title>You are offline</title>

    <!-- Inline the page's stylesheet. -->
    <style>
      body {
        font-family: helvetica, arial, sans-serif;
        margin: 2em;
      }

      h1 {
        font-style: italic;
        color: #373fff;
      }

      p {
        margin-block: 1rem;
      }

      button {
        display: block;
      }
    </style>
  </head>
  <body>
    <h1>You are offline</h1>

    <p>Click the button below to try reloading.</p>
    <button type="button">⤾ Reload</button>

    <!-- Inline the page's JavaScript file. -->
    <script>
      // Manual reload feature.
      document.querySelector("button").addEventListener("click", () => {
        window.location.reload();
      });

      // Listen to changes in the network state, reload when online.
      // This handles the case when the device is completely offline.
      window.addEventListener('online', () => {
        window.location.reload();
      });

      // Check if the server is responding and reload the page if it is.
      // This handles the case when the device is online, but the server
      // is offline or misbehaving.
      async function checkNetworkAndReload() {
        try {
          const response = await fetch('.');
          // Verify we get a valid response from the server
          if (response.status >= 200 && response.status < 500) {
            window.location.reload();
            return;
          }
        } catch {
          // Unable to connect to the server, ignore.
        }
        window.setTimeout(checkNetworkAndReload, 2500);
      }

      checkNetworkAndReload();
    </script>
  </body>
</html>

演示

通过下方嵌入的演示,您可以查看离线回退页面的实际效果。如果您感兴趣,可以浏览 Glitch 上的源代码

有关使应用可安装的备注

既然您的网站已经有离线后备网页了,您可能想知道接下来该怎么做。如需让您的应用成为可安装的应用,您需要添加 Web 应用清单,并视需要制定安装策略

关于使用 Workbox.js 提供离线后备网页的备注

您可能听说过 Workbox。Workbox 是一组 JavaScript 库,用于向 Web 应用添加离线支持。如果您希望自己编写较少的 Service Worker 代码,可以针对离线页面使用 Workbox 配方。

接下来,请了解如何为应用定义安装策略