Offline Web Apps
What happens when the internet disappears? Learn how Service Workers and caching can keep important website resources available, even when you’re offline.
navigator.serviceWorker
.register("/sw.js");
caches.open("app-v1");
Can a Website Work Without Internet?
Normally, a website requests files from a server. If the connection disappears, those requests may fail. But what if the browser had already saved the files it needed?
Modern web applications can use Service Workers and the Cache Storage API to store selected resources and make them available offline.
Think of it like packing a travel bag. Before leaving home, you save what you need so it’s available when you can’t connect.
Meet the Background Network Helper
A Service Worker is a JavaScript file that the browser can run separately from your webpage. Once installed and activated, it can intercept certain network requests made by pages it controls.
A Service Worker can help with caching, offline responses, and other background capabilities. It isn’t a permanently running script, and it cannot directly manipulate the webpage’s DOM.
if ("serviceWorker" in navigator) {
window.addEventListener("load", async () => {
try {
const registration =
await navigator.serviceWorker.register("/sw.js");
console.log("Registered:", registration.scope);
} catch (error) {
console.error("Registration failed:", error);
}
});
}The register() method tells the browser where the Service Worker script lives.
Save Files for Later
The Cache Storage API lets an application store request-and-response pairs. Unlike localStorage, it is designed for resources such as HTML pages, stylesheets, images, and scripts.
const cache = await caches.open("my-app-v1");
await cache.addAll([
"/",
"/styles.css",
"/app.js"
]);These paths are examples. In a real project, every file must exist and be accessible, or addAll() can fail.
Cache Storage and Service Workers are related, but they aren’t the same thing: a page can use Cache Storage directly, while a Service Worker can use it to answer network requests.
Prepare the Offline Experience
Service Workers have lifecycle events. The install event is commonly used to cache essential files, while activate is often used to clean up outdated caches.
const CACHE_NAME = "my-app-v1";
const FILES = ["/", "/styles.css", "/app.js"];
self.addEventListener("install", event => {
event.waitUntil(
caches.open(CACHE_NAME).then(cache => {
return cache.addAll(FILES);
})
);
});
self.addEventListener("activate", event => {
event.waitUntil(
caches.keys().then(names =>
Promise.all(
names.filter(name =>
name.startsWith("my-app-") &&
name !== CACHE_NAME
).map(name => caches.delete(name))
)
)
);
});Using a versioned cache name helps developers replace old resources when an application changes.
Use the Cache When the Network Fails
A Service Worker can listen for fetch events and decide whether to use the network or a cached response.
self.addEventListener("fetch", event => {
if (event.request.method !== "GET") return;
if (new URL(event.request.url).origin !==
self.location.origin) return;
event.respondWith(
fetch(event.request).catch(async () => {
const saved = await caches.match(event.request);
return saved || Response.error();
})
);
});This simplified example tries the network first and then looks in the cache if the network request fails. It does not automatically cache successful new responses.
Other strategies include cache-first for relatively stable assets and stale-while-revalidate for showing cached content while updating it in the background.
Try an Offline Cache Simulation
Use this example to explore the idea behind offline caching. First save a resource while online. Then switch to offline mode and try opening it again.
A short guide that can be saved for offline reading.
This is a learning simulation using JavaScript state, not a real network connection or Service Worker. The offline switch changes the simulated network status only.
Design Offline Experiences Carefully
- Cache only the resources your application needs.
- Give visitors useful messages when something isn’t available offline.
- Plan how cached content will be updated.
- Use HTTPS and test the Service Worker lifecycle.
- Be careful with personal information and authenticated responses.
- Remember that browsers may remove cached data under storage pressure.
- Test both the first visit and return visits with the network disabled.
Build an Offline Resource Simulator
Create a mini app that demonstrates what happens when someone tries to open a resource online, offline, and after caching it.
Your Mission
- Create a resource card with a title and short description.
- Add buttons to switch between simulated online and offline modes.
- Add a Cache Resource button that saves a copy in JavaScript state.
- Add an Open Resource button.
- Allow the resource to open offline only when it has been cached.
- Add a Clear Cache button.
- Show helpful status messages for every action.
Build Your Offline Cache Simulator!
Edit the code and click Run Code to preview your app. Start with the basic online/offline switch, then use Load Solution to explore a complete caching simulation.
What You’ve Learned
You’re Thinking Beyond the Network!
You now understand how modern websites can prepare for unreliable connections and provide a better offline experience.
- What Service Workers do and how they are registered.
- How Cache Storage stores web resources.
- How install, activate, and fetch events work.
- Why cache strategies and versioning matter.
- How to design and test an offline experience.
Next up: Web Workers — learn how to run JavaScript tasks in the background without blocking the main page!
Your Learning Journey
0 / 13 CompletedKeep going! Every completed lesson brings you closer to mastering Advanced HTML.
Nice Work!
You've explored how Service Workers and caching help websites prepare for offline use. You've also built a simulation that demonstrates how saved resources can remain available without a connection!


