Vanilla JavaScript Projects

Project 21, PWA and offline

Offline-first Todo PWA

Install it like an app, turn off your Wi-Fi, and keep working. The service worker serves the page from cache and your tasks never leave the device.

Main API
Service Worker, Cache
Saves to
IndexedDB
Files
index.html, sw.js, manifest
Your browser
Checking

Today

Online

Registering service worker

    How it works

    1. Install the workerOn first load, sw.js caches index.html, the manifest and the fonts.
    2. Serve from cacheEvery later request is answered from the cache first, so the page opens instantly and works with no network.
    3. Keep data localTasks live in IndexedDB. There is no server, so offline and online behave the same.
    // sw.js: cache the app shell, then answer from cache first
    const CACHE = "todo-v1";
    self.addEventListener("install", (e) => {
      e.waitUntil(caches.open(CACHE).then((c) => c.addAll(["./", "./index.html", "./manifest.webmanifest"])));
    });
    self.addEventListener("fetch", (e) => {
      e.respondWith(caches.match(e.request).then((hit) => hit || fetch(e.request).then((res) => {
        const copy = res.clone(); caches.open(CACHE).then((c) => c.put(e.request, copy)); return res;
      })));
    });
    // index.html
    navigator.serviceWorker.register("sw.js");