Offline HTML Applications
By the end of this lesson you will be able to keep a web app working when the network drops: pick a caching strategy for each kind of file, show your own offline page, clean up old caches, save user data in IndexedDB and show offline status clearly.
What you should know first: Service Workers Fundamentals (registration, the lifecycle, the fetch event and the Cache API), Fetch API Integration, Web Storage: LocalStorage and live regions from HTML Accessibility Fundamentals.
Offline-first thinking
Think of Isha on a train from Rohtak to Delhi. Her phone has full signal at the station, none near the fields, and one useless bar near the next town. Many Indian users live with patchy networks like this every day.
A normal website assumes the network is always there and shows the browser's "No internet" page when it fails. An offline-first app shows what is already saved on the device straight away, and uses the network to fetch fresher data when it can. Like a kirana shop, it sells from its own shelf and phones the wholesaler only for fresh stock.
Design for three network states, not two:
| State | A normal site | An offline-first app |
|---|---|---|
| Online and fast | Works | Works, and saves copies for later |
| Offline | Browser error page | Shows saved content and says it is offline |
| "Lie-fi": connected, but nothing loads | A spinner that never stops | Gives up after a few seconds and shows saved content |
What to store, and where
| What | Example | Where to keep it |
|---|---|---|
| App shell: the files that draw the empty app | index.html, app.js, icons | Cache API, saved during install (precaching) |
| Pages the user visited | /jetty/vypin | Cache API, saved as they load (runtime caching) |
| Data from your server | /api/ferries.json | Cache API for whole responses |
| The user's own data | favourite routes, a draft form | IndexedDB |
| Tiny settings | theme, language | localStorage |
The app shell is the skeleton of your interface without the changing data. Precaching means saving it before the user needs it. IndexedDB is a database in the browser that stores JavaScript objects you can read and update one at a time.
Caching strategies
A caching strategy is the rule your service worker follows to answer a request: look in the cache, go to the network, or both. Here are the three you will use most, as functions for the fetch handler of a ferry timetable app in Kochi.
Cache first answers from the cache and goes to the network only when nothing is saved. It is fast and works offline, but users may see old files. Use it for files that never change at the same URL, such as app.3f9a1c.js or icons.
const RUNTIME = "ferry-runtime-v1";
async function cacheFirst(request) {
const cached = await caches.match(request);
if (cached) return cached;
const response = await fetch(request);
if (response.ok) {
const cache = await caches.open(RUNTIME);
cache.put(request, response.clone());
}
return response;
}response.clone() is needed because a response body can be read only once: one copy goes into the cache, the other goes to the page.
Network first tries the network, saves a copy, and falls back to the cache when the network fails. Use it for pages and data that change often. On lie-fi, fetch() can hang for a minute, so race it against a timeout.
function timeout(ms) {
return new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), ms));
}
async function networkFirst(request) {
const cache = await caches.open(RUNTIME);
try {
const response = await Promise.race([fetch(request), timeout(4000)]);
if (response.ok) cache.put(request, response.clone());
return response;
} catch {
const cached = await cache.match(request);
if (cached) return cached;
throw new Error("Offline and not cached");
}
}Stale-while-revalidate answers from the cache at once and fetches a fresh copy in the background for next time. Use it for timetables, price lists or profile pictures.
async function staleWhileRevalidate(event) {
const cache = await caches.open(RUNTIME);
const cached = await cache.match(event.request);
const fresh = fetch(event.request).then((response) => {
if (response.ok) cache.put(event.request, response.clone());
return response;
});
if (cached) {
event.waitUntil(fresh.catch(() => {})); // keep the worker alive for the update
return cached;
}
return fresh;
}Network only means not calling respondWith() at all. Use it for payments and logins, which must never be stored.
Step 1 is to write the functions. Step 2 is a router that picks one for each request:
self.addEventListener("fetch", (event) => {
const { request } = event;
const url = new URL(request.url);
if (request.method !== "GET" || url.origin !== location.origin) return; // network only
if (request.mode === "navigate") {
event.respondWith(networkFirst(request).catch(() => caches.match("/offline.html")));
} else if (url.pathname.startsWith("/api/")) {
event.respondWith(staleWhileRevalidate(event));
} else {
event.respondWith(cacheFirst(request));
}
});request.mode === "navigate" is true when the browser loads a whole page. Only GET requests can be cached; cache.put() throws an error for a POST.
| Strategy | Speed | Freshness | Offline | Good for |
|---|---|---|---|---|
| Cache first | Fastest | Can be old | Yes | Versioned CSS, JS, fonts, icons |
| Network first | Waits for network | Freshest | Yes, after one visit | Pages, account data |
| Stale-while-revalidate | Fast | One visit behind | Yes, after one visit | Timetables, prices, avatars |
| Network only | Waits for network | Fresh | No | Payments, logins, analytics |
Try the strategies
Service workers cannot be registered from the Try-it editor, because your code runs in a sandboxed frame with no worker script of its own. The Cache API, however, also works in normal pages through window.caches. This lab uses a real cache and a pretend server, so you can watch each strategy decide.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Caching strategy lab</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; }
.row { display: flex; flex-wrap: wrap; gap: 8px; margin-block: 8px; }
#log { font-family: monospace; background: #f5f5f5; padding: 8px 8px 8px 32px; }
</style>
</head>
<body>
<h1>Caching strategy lab</h1>
<p>Server copy: <strong id="server">Timetable v1</strong></p>
<div class="row">
<button type="button" id="publish">Publish a new version</button>
<label><input type="checkbox" id="down"> Network is down</label>
<button type="button" id="empty">Empty the demo cache</button>
</div>
<div class="row">
<button type="button" data-strategy="cacheFirst">Cache first</button>
<button type="button" data-strategy="networkFirst">Network first</button>
<button type="button" data-strategy="staleWhileRevalidate">Stale-while-revalidate</button>
</div>
<ol id="log" aria-live="polite"></ol>
<script>
const CACHE = "demo-strategy-lab";
const KEY = "https://example.com/demo/timetable.txt"; // only a cache key, never fetched
let serverVersion = 1;
// A pretend server: slow, and it fails when "Network is down" is ticked
async function fakeFetch() {
await new Promise((r) => setTimeout(r, 600));
if (document.querySelector("#down").checked) throw new TypeError("Failed to fetch");
return new Response(`Timetable v${serverVersion}`);
}
function log(text) {
const li = document.createElement("li");
li.textContent = text;
document.querySelector("#log").append(li);
}
const strategies = {
async cacheFirst(cache) {
const hit = await cache.match(KEY);
if (hit) return ["cache", hit];
const res = await fakeFetch();
await cache.put(KEY, res.clone());
return ["network", res];
},
async networkFirst(cache) {
try {
const res = await fakeFetch();
await cache.put(KEY, res.clone());
return ["network", res];
} catch {
const hit = await cache.match(KEY);
if (hit) return ["cache (network failed)", hit];
throw new Error("offline and nothing saved");
}
},
async staleWhileRevalidate(cache) {
const hit = await cache.match(KEY);
const update = fakeFetch().then(async (res) => {
await cache.put(KEY, res.clone());
return res;
});
if (hit) {
update
.then(async (res) => log(` background update saved "${await res.text()}"`))
.catch(() => log(" background update failed, old copy kept"));
return ["cache, updating in background", hit];
}
return ["network", await update];
}
};
document.querySelectorAll("[data-strategy]").forEach((button) => {
button.addEventListener("click", async () => {
const name = button.dataset.strategy;
try {
const cache = await caches.open(CACHE);
const [from, res] = await strategies[name](cache);
log(`${name}: "${await res.text()}" from ${from}`);
} catch (err) {
log(`${name}: failed (${err.message})`);
}
});
});
document.querySelector("#publish").addEventListener("click", () => {
serverVersion++;
document.querySelector("#server").textContent = `Timetable v${serverVersion}`;
});
document.querySelector("#empty").addEventListener("click", async () => {
await caches.delete(CACHE);
log("demo cache emptied");
});
</script>
</body>
</html>Try this order and watch the log:
- Click Cache first (v1 from the network), Publish a new version, then Cache first again: still v1, from the cache.
- Click Network first: v2 arrives and replaces the saved copy.
- Publish again and click Stale-while-revalidate twice. The first click shows v2 and saves v3 in the background; the second shows v3.
- Tick Network is down: network first and stale-while-revalidate fall back to the saved copy.
- Empty the demo cache with the network down: everything fails. This is why you precache the app shell.
Precache the app shell and add an offline page
Step 1: list the shell files and save them in the install event.
const VERSION = "v3";
const SHELL = `ferry-shell-${VERSION}`;
const SHELL_FILES = ["/", "/styles.css", "/app.js", "/offline.html", "/icons/icon-192.png"];
self.addEventListener("install", (event) => {
event.waitUntil(caches.open(SHELL).then((cache) => cache.addAll(SHELL_FILES)));
});cache.addAll() is all or nothing. If one file returns 404, the whole install fails and the old worker stays in charge. This prevents a half-saved app, but one typing mistake in the list blocks every update.
Step 2: write offline.html. Keep it self-contained, with CSS inside the page and no outside images or fonts, because those may not be cached.
<!DOCTYPE html>
<html lang="en-IN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Offline: Kochi Ferry Times</title>
<style>body { font-family: system-ui, sans-serif; padding: 16px; }</style>
</head>
<body>
<h1>You are offline</h1>
<p>This page is not saved on your phone yet. The <a href="/">ferry timetable</a> still works.</p>
</body>
</html>Step 3: the router you wrote earlier already serves it when a page load fails. caches.match() searches every cache of your site, so the shell cache is included.
Versioned caches and cleanup
Each time you deploy, change VERSION. The new worker installs into ferry-shell-v4 while pages still open use v3. When the new worker activates, delete what it no longer needs.
self.addEventListener("activate", (event) => {
event.waitUntil((async () => {
const keep = [SHELL, RUNTIME];
for (const name of await caches.keys()) {
if (name.startsWith("ferry-") && !keep.includes(name)) {
await caches.delete(name);
}
}
})());
});Why in activate and not in install? While the new worker waits, old pages still need the v3 files. Why the ferry- prefix? Other apps may share your origin, and deleting their caches would break them.
Storage is not unlimited. A browser may evict (delete) a site's data when the phone runs low on space. navigator.storage.estimate() reports usage and quota, and navigator.storage.persist() asks the browser to keep your data. It may refuse, so always handle an empty cache.
IndexedDB for the user's data
Responses go in the Cache API. Records the user creates, such as favourite ferry routes, belong in IndexedDB. Its API uses events, so small promise helpers make it easier:
function openDb() {
return new Promise((resolve, reject) => {
const req = indexedDB.open("ferry-app", 1);
req.onupgradeneeded = () => req.result.createObjectStore("favourites", { keyPath: "route" });
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
async function saveFavourite(trip) {
const db = await openDb();
const tx = db.transaction("favourites", "readwrite");
tx.objectStore("favourites").put(trip);
return new Promise((resolve, reject) => {
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
}
async function getFavourites() {
const db = await openDb();
return new Promise((resolve, reject) => {
const req = db.transaction("favourites").objectStore("favourites").getAll();
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
await saveFavourite({ route: "Fort Kochi", time: "07:10", jetty: 2 });
await saveFavourite({ route: "Fort Kochi", time: "07:10", jetty: 3 });
console.log(JSON.stringify(await getFavourites()));[{"route":"Fort Kochi","time":"07:10","jetty":3}]keyPath: "route" makes the route name the key, so the second put() replaces the first record. IndexedDB works in pages and service workers, and holds far more than localStorage.
Tell users when they are offline
navigator.onLine is false when the device has no network at all, and true for any connection, even Wi-Fi with no internet behind it. Treat false as certain and true as "maybe". The online and offline events fire on window when it changes.
Put the message in a live region, an element whose text changes screen readers announce. role="status" is polite: it waits until the reader finishes speaking. Do not hide content when offline; disable only actions that need the network.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Network status banner</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; }
#banner { padding: 10px 14px; border-radius: 8px; background: #e8f5e9; color: #1b5e20; }
#banner.offline { background: #fff3e0; color: #8a3b00; }
</style>
</head>
<body>
<h1>Kochi Ferry Times</h1>
<p id="banner" role="status"></p>
<button type="button" id="refresh">Refresh timings</button>
<h2>Event log</h2>
<ol id="log"></ol>
<script>
const banner = document.querySelector("#banner");
const refresh = document.querySelector("#refresh");
function showStatus(reason) {
const online = navigator.onLine;
banner.textContent = online
? "Online. Timings will refresh."
: "Offline. You are seeing saved timings. Refresh is paused.";
banner.classList.toggle("offline", !online);
refresh.disabled = !online;
const item = document.createElement("li");
item.textContent = `${new Date().toLocaleTimeString("en-IN")}: ${reason}, navigator.onLine is ${online}`;
document.querySelector("#log").append(item);
}
window.addEventListener("online", () => showStatus("online event"));
window.addEventListener("offline", () => showStatus("offline event"));
showStatus("page loaded");
</script>
</body>
</html>To test it, open DevTools (F12), go to the Network tab and change the throttling menu from "No throttling" to Offline. The banner turns orange, the button is disabled and the log shows an offline event. Switch back and an online event appears.
Test offline behaviour in DevTools
On your real app, served from localhost or HTTPS:
- Application > Service workers: the worker should be "activated and is running".
- Application > Cache storage: every shell file should be listed.
- Tick Offline in the Service workers pane and reload. The page should still appear.
- Open a URL you never visited. Your
offline.htmlshould appear. - Pick a slow throttling preset such as 3G to test the network-first timeout.
- Application > Storage > Clear site data starts you again as a new visitor.
Common mistakes
- Network first with no timeout. On lie-fi users wait a minute for a fallback.
- Forgetting to change the version. Users keep the old shell for ever.
- Deleting every cache in
activate. Delete only your own prefix and old versions. - Caching error pages. Check
response.okbeforecache.put(). - Trusting
navigator.onLine === true. It means "some connection", not "internet works". - An offline page that loads outside fonts or images. They fail exactly when needed.
Interview questions
1. Explain cache first, network first and stale-while-revalidate.
Cache first fetches only on a cache miss: fast, but possibly stale. Network first falls back to the cache when the network fails: fresh when possible. Stale-while-revalidate answers from the cache at once and updates it in the background for the next visit.
2. Why should a network-first strategy have a timeout?
On a weak connection fetch() may neither succeed nor fail for a long time, so the user stares at a blank page although a cached copy exists. Racing fetch() against a short timer gives a quick fallback.
3. Why do we delete old caches in activate instead of install?
During install, the old worker still controls open pages that need the old files. A new worker normally activates only after those pages close, so activate is the first safe moment to delete old versions.
4. Is navigator.onLine reliable?
Only partly. false reliably means no network, but true only means some network exists, maybe without internet. Treat failed or slow requests as offline too.
5. Where would you store offline data: Cache API, IndexedDB or localStorage?
The Cache API stores whole HTTP responses, so it suits files and API responses. IndexedDB stores records you can query and update, such as drafts. localStorage is small and synchronous, so keep it for tiny settings.
Key points
- Offline-first apps show saved content first; design for online, offline and lie-fi.
- Use cache first for versioned files, network first (with a timeout) for pages, stale-while-revalidate for changing data, network only for payments.
- Precache the app shell in
installwithcache.addAll(), and serve a self-containedoffline.htmlwhen a page load fails. - Name caches with a prefix and version, and delete old versions in
activate. - Keep user records in IndexedDB; keep
localStoragefor tiny settings. - Show offline status in a
role="status"live region and disable only actions that need the network.
Exercise
Aarav is building "Jaipur Mandi Prices", which shows daily vegetable prices from /api/prices.json. Write the service worker. It must precache /, /styles.css, /app.js and /offline.html in a versioned cache, use stale-while-revalidate for /api/ requests, network first with a 3 second timeout for page loads (falling back to the cached page, then offline.html), cache first for everything else on the same origin, and delete old mandi- caches on activate.
Show solution
const VERSION = "v1";
const SHELL = `mandi-shell-${VERSION}`;
const RUNTIME = `mandi-runtime-${VERSION}`;
const SHELL_FILES = ["/", "/styles.css", "/app.js", "/offline.html"];
self.addEventListener("install", (event) => {
event.waitUntil(caches.open(SHELL).then((c) => c.addAll(SHELL_FILES)));
});
self.addEventListener("activate", (event) => {
event.waitUntil((async () => {
for (const name of await caches.keys()) {
if (name.startsWith("mandi-") && name !== SHELL && name !== RUNTIME) await caches.delete(name);
}
})());
});
const timeout = (ms) => new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), ms));
async function page(request) {
try {
const response = await Promise.race([fetch(request), timeout(3000)]);
if (response.ok) (await caches.open(RUNTIME)).put(request, response.clone());
return response;
} catch {
return (await caches.match(request)) || caches.match("/offline.html");
}
}
async function prices(event) {
const cache = await caches.open(RUNTIME);
const cached = await cache.match(event.request);
const fresh = fetch(event.request).then((r) => {
if (r.ok) cache.put(event.request, r.clone());
return r;
});
if (cached) {
event.waitUntil(fresh.catch(() => {}));
return cached;
}
return fresh;
}
async function asset(request) {
return (await caches.match(request)) || fetch(request);
}
self.addEventListener("fetch", (event) => {
const url = new URL(event.request.url);
if (event.request.method !== "GET" || url.origin !== location.origin) return;
if (event.request.mode === "navigate") event.respondWith(page(event.request));
else if (url.pathname.startsWith("/api/")) event.respondWith(prices(event));
else event.respondWith(asset(event.request));
});Prices appear instantly and refresh in the background, pages stop waiting after 3 seconds, and only old mandi- caches are deleted.
Quick Quiz
1. Which strategy shows saved data instantly and refreshes it in the background for next time?
It returns the cached copy and updates the cache behind the scenes.
2. cache.addAll() is given five files and one returns 404. What happens?
addAll() is all or nothing.
3. navigator.onLine is true. What does that tell you?
Only false is certain.
4. Which request should use "network only"?
Payments must never be answered from a cache.
Learn HTML with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
