mc0de
Advanced HTML · Lesson 11 of 13

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.

Service WorkersCache Storage Offline FirstInteractive Simulation
● ● ●   offline-app.js
navigator.serviceWorker
  .register("/sw.js");

caches.open("app-v1");
✓ Cached resources can work offline
01 / Getting Started

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.

Important: Offline support must be designed in advance. Simply visiting a website once doesn’t guarantee every page will work offline.
02 / Service Workers

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.

Register a Service Worker — main.js
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.

Real-world requirement: Service Workers generally require HTTPS or localhost. They also need a separately served JavaScript file with an appropriate scope. This lesson does not register a Service Worker on mC0de.
03 / Cache Storage

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.

Save selected resources
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.

04 / Install & Activate

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.

Example — sw.js (separate file)
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.

Production tip: Only delete caches your own application manages. On a shared website, broad cache deletion could affect unrelated features.
05 / Offline Fetching

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.

Example network-first strategy — sw.js
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.

06 / Interactive Demonstration

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.

📦 Resource: My Coding Guide

A short guide that can be saved for offline reading.

Online · Resource not cached
Choose “Open Resource” to view the guide.

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.

07 / Best Practices

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.
Important distinction: The old HTML Application Cache (AppCache) technology is obsolete. Modern offline web applications use Service Workers, Cache Storage, and related APIs.
🚀 mC0de Challenge

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

  1. Create a resource card with a title and short description.
  2. Add buttons to switch between simulated online and offline modes.
  3. Add a Cache Resource button that saves a copy in JavaScript state.
  4. Add an Open Resource button.
  5. Allow the resource to open offline only when it has been cached.
  6. Add a Clear Cache button.
  7. Show helpful status messages for every action.
Extra challenge: Add two different resources and allow visitors to cache them independently!
💻 Interactive HTML Sandbox

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.

Live Result
Sandbox note: This preview intentionally does not register a Service Worker or change the site’s actual network behavior. It’s an isolated environment for experimenting with the caching concept.
Lesson 11 Recap

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 Completed

Keep 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!