สร้างหน้าสำรองแบบออฟไลน์

แอป Google Assistant, แอป Slack, แอป Zoom และแอปเฉพาะแพลตฟอร์มอื่นๆ ในโทรศัพท์หรือคอมพิวเตอร์ของคุณมีอะไรบ้าง ใช่แล้ว อย่างน้อยพวกเขาก็ให้อะไรบางอย่างแก่คุณเสมอ แม้จะไม่ได้เชื่อมต่อเครือข่าย คุณก็ยังเปิดแอป Assistant, เข้าสู่ Slack หรือเริ่มซูมได้ คุณอาจไม่ได้รับสิ่งที่เป็นประโยชน์ใดๆ เลย หรือแม้กระทั่งไม่สามารถบรรลุสิ่งที่อยากทำให้สำเร็จ แต่อย่างน้อยคุณก็มีบางสิ่ง และแอปจะควบคุมข้อมูลได้

แอป Google Assistant บนอุปกรณ์เคลื่อนที่ขณะออฟไลน์
Google Assistant

แอป Slack บนอุปกรณ์เคลื่อนที่ขณะออฟไลน์
Slack

แอป Zoom บนอุปกรณ์เคลื่อนที่ขณะออฟไลน์
ซูม

เมื่อใช้แอปเฉพาะแพลตฟอร์ม แม้ว่าคุณจะไม่มีการเชื่อมต่อเครือข่าย คุณก็จะไม่ได้รับอะไรเลย

ในทางตรงกันข้าม เมื่อคุณออฟไลน์ โดยทั่วไปแล้วคุณจะไม่พบสิ่งใดเลย Chrome นำเสนอเกมไดโนเสาร์แบบออฟไลน์แก่คุณ

แอป Google Chrome บนอุปกรณ์เคลื่อนที่แสดงภาพเกมไดโนเสาร์แบบออฟไลน์
Google Chrome สำหรับ iOS

แอป Google Chrome บนเดสก์ท็อปแสดงภาพเกมไดโนเสาร์แบบออฟไลน์
Google Chrome สำหรับ macOS

เมื่อไม่มีการเชื่อมต่อเครือข่ายบนเว็บ คุณจะไม่เห็นอะไรเลยโดยค่าเริ่มต้น

หน้าสำรองแบบออฟไลน์ที่มี Service Worker ที่กำหนดเอง

แต่ไม่จำเป็นต้องเป็นแบบนี้ ด้วยโปรแกรมทำงานของบริการและ Cache Storage API คุณสามารถมอบประสบการณ์การใช้งานออฟไลน์ที่ปรับแต่งให้เหมาะกับผู้ใช้ได้ ซึ่งอาจเป็นหน้าแบรนด์แบบง่ายๆ ซึ่งมีข้อมูลว่าผู้ใช้ออฟไลน์อยู่ แต่ก็เป็นโซลูชันที่สร้างสรรค์มากขึ้นได้เช่นกัน อย่างเช่น เกมเขาวงกตออฟไลน์อันโด่งดังที่มีปุ่ม เชื่อมต่อใหม่ ด้วยตนเองและการนับถอยหลังการพยายามเชื่อมต่อใหม่โดยอัตโนมัติ

หน้า 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 ได้

หมายเหตุเพิ่มเติมเกี่ยวกับการทำให้ติดตั้งแอปได้

ตอนนี้เว็บไซต์ของคุณมีหน้าสำรองแบบออฟไลน์แล้ว คุณอาจสงสัยเกี่ยวกับขั้นตอนถัดไป หากต้องการให้แอปติดตั้งได้ คุณต้องเพิ่มไฟล์ Manifest ของเว็บแอปและอาจมีกลยุทธ์การติดตั้ง (ไม่บังคับ)

หมายเหตุเกี่ยวกับการแสดงหน้าสำรองแบบออฟไลน์ด้วย Workbox.js

คุณอาจเคยได้ยินเกี่ยวกับ Workbox Workbox คือชุดไลบรารี JavaScript สำหรับเพิ่มการสนับสนุนแบบออฟไลน์ลงในเว็บแอป หากต้องการเขียนโค้ด Service Worker น้อยลงด้วยตนเอง คุณใช้สูตร Workbox กับหน้าเว็บแบบออฟไลน์เท่านั้นได้

ถัดไป เรียนรู้วิธีกําหนดกลยุทธ์การติดตั้งสําหรับแอปของคุณ