Ứng dụng Trợ lý Google, ứng dụng Slack, ứng dụng Zoom và hầu hết mọi ứng dụng dành riêng cho nền tảng khác trên điện thoại hoặc máy tính của bạn có điểm gì chung? Đúng vậy, họ luôn cho bạn một thứ gì đó. Ngay cả khi không có kết nối mạng, bạn vẫn có thể mở ứng dụng Trợ lý, nhập Slack hoặc khởi chạy Zoom. Bạn có thể không nhận được thông tin gì đặc biệt có ý nghĩa hoặc thậm chí không đạt được mục tiêu, nhưng ít nhất bạn cũng nhận được thông tin nào đó và ứng dụng vẫn trong tầm kiểm soát.



Ngược lại, trên web, theo truyền thống, bạn sẽ không nhận được gì khi không có mạng. Chrome cung cấp cho bạn trò chơi khủng long khi không có mạng, nhưng chỉ có vậy thôi.


Một trang dự phòng khi không có mạng có trình chạy dịch vụ tuỳ chỉnh
Tuy nhiên, không nhất thiết phải như vậy. Nhờ các worker dịch vụ và Cache Storage API, bạn có thể mang đến trải nghiệm tuỳ chỉnh khi không có mạng cho người dùng. Đây có thể là một trang đơn giản có gắn thương hiệu với thông tin cho biết người dùng hiện đang ở chế độ ngoại tuyến, nhưng cũng có thể là một giải pháp sáng tạo hơn, chẳng hạn như trò chơi mê cung ngoại tuyến nổi tiếng của trivago với nút Kết nối lại theo cách thủ công và đồng hồ đếm ngược tự động cho lần thử kết nối lại.

Đăng ký trình chạy dịch vụ
Cách để thực hiện việc này là thông qua một service worker. Bạn có thể đăng ký một worker dịch vụ từ trang chính của mình như trong mẫu mã bên dưới. Thông thường, bạn sẽ thực hiện việc này sau khi ứng dụng đã tải.
window.addEventListener("load", () => {
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("service-worker.js");
}
});
Mã trình chạy dịch vụ
Nội dung của tệp worker thực tế có thể hơi phức tạp khi nhìn vào lần đầu, nhưng các nhận xét trong mẫu bên dưới sẽ giúp bạn hiểu rõ hơn. Ý tưởng cốt lõi là lưu trước vào bộ nhớ đệm một tệp có tên là offline.html
. Tệp này chỉ được phân phát trên các yêu cầu điều hướng không thành công và cho phép trình duyệt xử lý tất cả các trường hợp khác:
/*
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.
});
Trang dự phòng khi không có mạng
Tệp offline.html
là nơi bạn có thể thoả sức sáng tạo và điều chỉnh cho phù hợp với nhu cầu của mình, cũng như thêm thương hiệu của bạn. Ví dụ dưới đây cho thấy mức tối thiểu có thể đạt được.
Ứng dụng này minh hoạ cả tính năng tải lại thủ công dựa trên thao tác nhấn nút cũng như tính năng tải lại tự động dựa trên sự kiện online
và hoạt động thăm dò máy chủ thường xuyên.
<!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>
Bản minh hoạ
Bạn có thể xem trang dự phòng ngoại tuyến hoạt động trong bản minh hoạ được nhúng bên dưới. Nếu quan tâm, bạn có thể khám phá mã nguồn trên GitHub.
Lưu ý bên lề về cách giúp ứng dụng của bạn có thể cài đặt
Bây giờ, trang web của bạn đã có trang dự phòng ngoại tuyến, bạn có thể thắc mắc về các bước tiếp theo. Để có thể cài đặt ứng dụng, bạn cần thêm một tệp kê khai ứng dụng web và có thể đưa ra một chiến lược cài đặt.
Lưu ý bên lề về việc phân phát trang dự phòng khi không có mạng bằng Workbox.js
Có thể bạn đã nghe nói đến Workbox. Workbox là một bộ thư viện JavaScript để thêm tính năng hỗ trợ khi không có mạng vào các ứng dụng web. Nếu không muốn tự viết nhiều mã trình chạy dịch vụ, bạn có thể sử dụng công thức Workbox cho chỉ trang ngoại tuyến.
Tiếp theo, hãy tìm hiểu cách xác định chiến lược cài đặt cho ứng dụng của bạn.