DEV Community

Cover image for Your On-Device AI Works Offline. Does Your Web App?

Your On-Device AI Works Offline. Does Your Web App?

Tracks UI, model, and draft states independently

An on-device model can be ready without a network connection while the application around it still fails to reopen. The model works; the HTML, JavaScript, fonts, or saved input do not. From the user’s perspective, the feature is still offline and unavailable.

An offline promise therefore needs an interaction-level test. Close or reload the page without connectivity and check whether the person can recover their work, use the available features, and understand what is unavailable.

The companion implements a small React brief editor with local draft storage and a versioned application cache. Native AI remains optional and independently checked. The example does not queue bookings, synchronize accounts, or pretend that caching a shell turns a server-backed workflow into a complete offline application.

Track three independent kinds of readiness

The browser can have an application shell without a usable model, or a usable model without the application shell. The user’s draft is a third concern.

Resource Owner in this example Readiness question
HTML, JavaScript, CSS Application service worker Can the editor reopen?
Synthetic brief Application local storage Can the person recover the text?
Built-in AI model Browser Can the selected API perform this task?

Do not display a single “Offline ready” badge based only on successful service-worker registration. Registration does not establish that the worker controls this page, that all required assets were cached, or that the model can run.

Similarly, navigator.onLine is a connectivity hint. It cannot establish that a particular model endpoint or application API is reachable.

Cache the application shell deliberately

The build script collects the emitted HTML, JavaScript, and CSS and creates a cache name from their content hash. The generated service worker precaches that allowlist during installation.

self.addEventListener("install", event => {
  event.waitUntil(
    caches.open(CACHE).then(cache => cache.addAll(URLS))
  );
});
Enter fullscreen mode Exit fullscreen mode

CACHE and URLS are build-generated values, not placeholders in the delivered worker. If installation cannot obtain a required asset, it should fail rather than advertise a complete shell.

The example handles the root navigation with a network request and a cached fallback. Versioned assets use the active shell cache. Requests outside the same-origin allowlist are left alone.

This restriction matters. A broad “cache every GET” policy can capture personalized responses, unbounded resources, and data whose freshness rules differ from static application code. The lab has no authenticated API responses to cache.

Treat updates as an application decision

A new worker cleans up older caches bearing this application’s prefix when it activates. It does not delete unrelated caches from the origin.

The example also avoids forcing every new worker to activate immediately with skipWaiting(). Replacing the worker beneath an open editor can mix versions or interrupt work. A larger application should offer a controlled update after the person has saved or exported their draft.

Keep old assets available on the server for a suitable deployment window. A versioned cache helps a previously installed application, but it cannot rescue an asset that was never cached and has already been removed from the server.

Application assets, saved input, and model readiness independently determine whether editing and AI actions can work offline.

Figure 1. Offline editing and offline inference require different resources.

Preserve input without overstating storage

The demonstration stores a small synthetic brief in localStorage. Its write path catches failures and tells the person to copy the text before closing the page.

try {
  localStorage.setItem("web-ai-lab-brief", text);
} catch {
  setStorage("Local saving failed. Copy the brief before closing.");
}
Enter fullscreen mode Exit fullscreen mode

This is intentionally modest. Storage is not a backup, a multi-device sync mechanism, or an appropriate default for every confidential document. Real products need a retention policy, deletion controls, and storage choices that fit their data and size requirements.

For a richer editor, IndexedDB may be more appropriate. Preserve the same user-facing rule: a failed write must not leave an unqualified “Saved” indicator on screen.

Keep model storage separate

The lab’s service worker does not attempt to cache Chrome’s built-in model internals. The application asks the API about the requested task and handles preparation or unavailability through the normal UI.

If you serve your own model through a library such as LiteRT.js, those model files and runtime assets become part of your application’s delivery design. Give them explicit versions, integrity records, download behavior, and cache rules. The companion excludes its benchmark’s model and Wasm files from the small editor-shell cache so that opening the editor does not silently download the benchmark workload.

Chrome’s model-caching guidance discusses models served by applications. Apply it to that delivery path rather than assuming every built-in model is a resource your service worker controls.

Test a cold visit and a returning visit separately

Build the production bundle with npm run build, then serve it with npm run preview. The development server deliberately does not register the production worker.

First load the application online, save a synthetic brief, and wait for the worker to become ready. Reload to establish control, then disable connectivity and reload again. Verify that the editor appears and that the saved text is correct.

Now repeat in a fresh profile that has never visited the application. An offline first visit has no installed shell to use. That should be reported as an unsupported scenario, not folded into a returning-user success rate.

The browser script passed this controlled-worker reload case in Headless Chrome 153. After saving a synthetic brief and establishing worker control, it disabled connectivity, reloaded, and recovered the exact saved text. The evidence file and screenshot record that result. This verifies the editor and draft; model inference still requires its own native preparation and offline run.

Finally test missing assets, storage failures, and a model that is unavailable even though the editor opens. A successful warm model call while the page remains open does not cover any of those scenarios.

The practical goal is continuity: people can recover their text and understand the remaining options. Which part of your application’s offline promise have you verified after a complete reload?

References

Top comments (22)

Collapse
 
yogin_parmar profile image
Yogin Parmar •

The three-way split holds on native Android too, though the shell part comes free with the APK. Where we got caught was model readiness, which isn't a yes or no. Our offline model on a Snapdragon 695 first memory-mapped its weights, and Android evicted those pages mid-answer under memory pressure. The model was "available" the whole time, but speed fell to about 1 token a second. Loading the weights into RAM fixed it. So for us readiness now includes "can it answer at a usable speed right now", not just "is it there".

Does your lab's model check look at speed or warm-up time, or only whether the API reports the model as available?

Collapse
 
raju_dandigam profile image
Raju Dandigam Google Developer Experts •

@yogin_parmar That is a useful distinction. This lab’s automated offline check verifies that the shell reopens and the exact draft is restored; the native-AI path checks availability and preparation separately. It does not yet measure warm-up time, tokens per second, or slowdown under memory pressure, so I would not claim inference performance is verified. Your example suggests a valuable follow-up: compare cold launch and a resumed session under pressure, with latency and throughput thresholds. What threshold proved usable on that device?

Collapse
 
yogin_parmar profile image
Yogin Parmar •

@raju_dandigam I never set a formal threshold. On the Snapdragon 695 the 0.5B model generated about 12 tokens a second on 2 threads, and short answers felt fine at that speed when I tried them by hand. The mmap stall at about 1 token a second was clearly broken, and everything in between is untested. Cold launch vs a resumed session under memory pressure is the comparison I'm missing too. Would you gate on time to first token or on tokens per second?

Thread Thread
 
raju_dandigam profile image
Raju Dandigam Google Developer Experts •

@yogin_parmar I would measure both. Time to first token captures the cold-start pause; sustained tokens/sec captures whether the answer remains usable once it begins. Short replies may be dominated by the first, while longer ones expose the 1-token/sec stall. I'd record cold and resumed runs under memory pressure separately, then choose thresholds from a small device test rather than claim one universal number. Your 12 vs. 1 tokens/sec result is a good regression fixture.

Thread Thread
 
yogin_parmar profile image
Yogin Parmar •

Splitting cold and resumed runs makes sense. Our 1 tok/s case was the resumed kind: the model still counted as loaded, but its mmap pages had been evicted. I'll log time to first token and the steady rate for each run on the SD695 and keep the 12 vs 1 pair as the regression fixture. When you test under memory pressure, do you fill RAM from a second app or use a test hook?

Thread Thread
 
raju_dandigam profile image
Raju Dandigam Google Developer Experts •

@yogin_parmar I have not run that pressure test yet. For a device-level regression I would use a separate workload to create real memory pressure, record free memory and process state, then repeat the same prompt after backgrounding and resuming. A test hook could make the scenario repeatable, but I would keep it as a separate lane because it may not reproduce the OS eviction path. Your 12 versus 1 tok/s pair is a useful failure fixture, with time to first token reported beside steady throughput.

Thread Thread
 
yogin_parmar profile image
Yogin Parmar •

That split makes sense. I'll keep the pressure test as its own lane and log time to first token next to tok/s, so a slow start and slow steady output don't get folded into one number.

Collapse
 
sherotree profile image
Sherotree •

The line I'd add to the checklist is the install path: if a required asset can't be cached, the worker should fail installation rather than advertise a complete shell. A green "offline ready" badge after a partial addAll is how you end up with an editor that reopens minus a font or a JS chunk. I'd also keep the allowlist tight — a broad cache-every-GET policy is how personalized or unbounded responses end up in the shell cache, which is a different failure than a missing draft.

Collapse
 
parimalmakes profile image
Parimal Makes •

the point about not calling skipWaiting() on an open editor is so true, swapping the worker while someone is typing is an easy way to mix versions
keeping model weights out of the shell cache also makes a lot of sense so the editor stays light to install

Collapse
 
raju_dandigam profile image
Raju Dandigam Google Developer Experts •

@parimalmakes Exactly. The new worker should wait while someone is editing, with the update offered after the draft is saved or exported. Keeping model files outside the shell cache also lets the editor reopen without making its first install carry the model download. An old-tab/new-deployment regression case would be a useful next check.

Collapse
 
ascendra_ventures_92c21f2 profile image
Ascendra Ventures •

Tracking three kinds of readiness separately, the shell, the model and the user's draft, is the useful split here. A model that runs offline inside an app that cannot reopen is a feature nobody can reach, and the comment about requesting persistent storage instead of trusting a successful write is a good addition.

Ascendra Ventures faced a related choice on a small browser product, a dashboard for Actofit body-composition scales built after the official app stopped returning the full readout. It reads the scale over Web Bluetooth in the browser, with no app install and no cloud middleman. The scale only sends two raw numbers, weight and bioelectrical impedance, and the app recomputes BMI, body fat and skeletal lean mass from the user's profile with the openScale/Xiaomi body-composition model. That split matters for your point: the readings are what belong to the user, and everything derived from them can be rebuilt.

In your editor example, would you treat the saved draft as the only thing that must survive a storage-pressure eviction, and simply rebuild the rest on the next online visit?

Collapse
 
paullovelace profile image
Paul Lovelace •

The cold-visit vs returning-visit split is the detail I'd steal — testing a fresh profile that never visited the app, and reporting offline-first-visit as unsupported instead of folding it into the returning-user success rate. That's the honest number most offline demos never show. Did the cold visit fail cleanly in your test, or was there a half-loaded state that looked worse than a straight 'not supported'?

Collapse
 
raju_dandigam profile image
Raju Dandigam Google Developer Experts •

@paullovelace The recorded automated run covered a returning visit after the worker had taken control; I haven't captured a fresh-profile, offline-first run as evidence yet. With no cached shell I'd expect the browser's offline error, but I shouldn't claim it failed cleanly until that run is recorded. A useful next fixture is a fresh profile with connectivity disabled before the first navigation, checking the visible state and that no partial editor appears.

Collapse
 
botsailorofficial profile image
BotSailor •

This is such an important point that often gets overlooked when building on-device AI applications. Having a model that works offline is great, but the overall experience still depends on whether the rest of the application can function without a reliable internet connection. I really like this reminder that offline-first design should be a complete architectural decision, not just a feature added to the AI layer. Things like local data storage, synchronization, graceful error handling, and conflict resolution make a huge difference in real-world usability. At the end of the day, users care less about where the AI runs and more about whether the product works when they actually need it. Great engineering perspective!

Collapse
 
gautamtalksdev profile image
Gautam K •

Good catch. A model that is ready offline means nothing if the shell won't load. A service worker that caches the app and keeps unsent input locally is the boring half that makes the AI half usable.

Collapse
 
raju_dandigam profile image
Raju Dandigam Google Developer Experts •

@gautamtalksdev Exactly. I’d make the offline reload check assert all three separately: the worker controls the page, the editor reopens with the exact unsent text, and the UI explains when the model is unavailable. A cached shell alone should never turn the overall status green, and a failed local write should never display ‘Saved.’

Collapse
 
gautamtalksdev profile image
Gautam K •

Asserting those three separately is the right move. A cached shell turning the whole status green, or 'Saved' showing after a failed local write, are exactly the false passes that hurt users most.

Collapse
 
gautamtalksdev profile image
Gautam K •

Asserting all three separately is a good call, since each one can fail on its own and a single combined check would hide which part broke.

Collapse
 
syedfahads profile image
Syed Fahad •

localStorage for the draft is fine for a demo, but without navigator.storage.persist() the browser can clear it under storage pressure. worth a line next to the failed write handling?

Collapse
 
raju_dandigam profile image
Raju Dandigam Google Developer Experts •

@syedfahads Yes, that deserves a note next to the failed-write path. I would request persistence where supported, show whether the browser granted it, and test a storage-pressure case rather than treating a successful write as durable. Even with persistence granted, this small local draft should still have an export path; it is not a backup or multi-device sync.

Collapse
 
the_daily_flare profile image
The daily flare •

Not calling skipWaiting on an open editor changed how I will handle updates in my own work.

Collapse
 
raju_dandigam profile image
Raju Dandigam Google Developer Experts •

@the_daily_flare Glad that was useful. The case I would test is an old tab with an unsaved edit when a new worker finishes installing: keep the old version serving that tab, show an update prompt only after the draft is safely saved or exported, then confirm the new version restores the same text. That catches the version-mixing problem the happy-path update test misses.