Model Loading and Caching in the Browser

Model Loading and Caching in the Browser

A model that outweighs the rest of your page needs its own delivery discipline: progressive download, browser storage choices, version-pinned cache keys, and first-run economics.

A client-side model runs from tens of megabytes to several gigabytes, roughly one to three orders of magnitude heavier than the median web page as a whole, and it must never sit in the critical path — the page renders, works, and stays interactive before a single weight downloads. This article covers getting those bytes down efficiently, choosing where they live once downloaded, versioning them so upgrades never leave two users silently running different models, and the first-run-versus-repeat-run economics that decide whether the feature feels native or punitive.

The model is not a bundle asset

The first honest fact is a matter of scale. Model weights run from tens of megabytes for a small task model (the quantized ONNX build of the all-MiniLM-L6-v2 embedding model is about 23 MB) to several gigabytes for larger language models (WebLLM's prebuilt Llama-3.1-8B-Instruct q4f16_1 weights are about 4.5 GB on the Hugging Face Hub, as of November 2026), while the median web page as a whole weighs a little over two megabytes (2,412 KB on desktop and 2,164 KB on mobile in the HTTP Archive Web Almanac 2025) — the ordinary instincts around bundling, preloading, and "just import it" break down once an asset is roughly one to three orders of magnitude larger than everything around it.

The cardinal rule follows directly from that scale mismatch: a model artifact never sits in the critical path. The page renders, functions, and stays interactive with zero model weights downloaded — the model is a capability the page acquires when needed, not a dependency the page blocks on before it can be used at all.

Deferring until intent is the practical form of that rule. Weights download on feature use or on explicit opt-in, never automatically on page load. The capable-versus-willing distinction this topic draws elsewhere — that a device being able to run a model is a different question from a user wanting to pay for the download right now — lands here as a concrete decision: capability determines whether the download is offered, willingness determines whether it starts. General page-loading performance, bundle budgets, and Core Web Vitals belong to their own literature; this article owns the model artifact specifically, once the page has already decided to fetch it.

The practical effect of getting this wrong is visible immediately in any performance trace: a model bundled the way a script chunk is bundled inflates every page load for every visitor, whether or not that visitor ever triggers the feature the model exists to serve. Treating the model as page weight rather than as an on-demand capability is an easy mistake to make when a working demo moves into a real product.

Getting the bytes down

Progressive, resumable download is the correct baseline posture, not an optimization to add later. Where the model host supports range requests, chunked fetching and resuming from where a transfer left off rather than restarting from zero matter enormously at this size. Range requests are an optional HTTP feature and a server may ignore the Range header, though the standard says origin servers and intermediate caches ought to support byte ranges when possible because byte ranges support efficient recovery from partially failed transfers and partial retrieval of large representations (RFC 9110 §14 and §14.2). A 300 MB download that restarts from the beginning after one dropped connection is close to a feature-killer on its own.

The compression reality is worth stating plainly because it tempers the instinct to reach for gzip. Lossless compression of model weights is not nothing: the ZipNN paper (arXiv:2411.05239) reports that compression tailored to neural networks often saves 33% and at times over 50% of model size on popular models, and that ZipNN's space savings on popular models such as Llama 3 are over 17% better than vanilla compression. Whether similar gains hold for the 4-bit quantized files that runtimes such as WebLLM ship is worth measuring before counting on it. The dependable wins come from serving the artifact close to the user, caching it hard at the edge, and — most of all — never downloading it twice for the same browser. Compression can help, but it is not where the biggest savings live.

Metered connections deserve a courtesy gate of their own. The Save-Data signal, where a browser exposes it, is a reasonable trigger for flipping the default from "download on use" to "ask first" — stating the size plainly before committing a user's data plan to it. How that consent and progress get presented to the user belongs to the inference-UX side of this topic; this article stops at the mechanics and the decision to gate.

The runtimes engineers actually reach for have already solved parts of this. By default, Transformers.js fetches from the Hugging Face Hub and caches files with the Cache API where that API is available, and WebLLM maintains its own artifact cache for the model libraries it loads — the Cache API by default, with IndexedDB, OPFS, and an experimental cross-origin extension backend as options (as of Transformers.js 4.3.2 and WebLLM v0.2.88, November 2026) — both worth treating as worked examples of the pattern rather than as prescriptions. Caching behavior in actively developed runtimes shifts between releases, so check the documentation for the version you ship.

Where the weights live

Three browser storage mechanisms compete for this job, and an honest comparison treats each on its own terms rather than declaring a single winner.

StorageAccess patternFit for model weights
Cache APIURL-addressed, request/response pairsService-worker-friendly, natural fit for fetched artifacts
OPFSFile-shaped; async on the main thread and in workers, synchronous access handles in dedicated workers onlyFast random access, good for large binary blobs
IndexedDBKey-value, broad legacy supportWorkable but awkward for very large blobs

Quota and eviction govern all three, regardless of which one a feature chooses. Storage is scoped per origin and, by default ("best-effort" mode), evictable under storage pressure — the Storage Standard says a browser under storage pressure should clear network state and best-effort local storage buckets, ideally in the way that least impacts the user. Storage that has been made persistent cannot be cleared by the browser without involvement from the origin or the user. Requesting persistent storage is asking a question, not making a guarantee; the browser can decline. And the StorageManager estimate call is the honest pre-check before committing to a large write: asking for the origin's approximate usage and quota before attempting the write. The standard keeps both figures estimates — usage is an implementation-defined rough estimate, and the quota is an implementation-defined conservative estimate that should be less than the device's total storage space and must not be a function of its available storage space — so the write can still fail and needs its own error handling.

The design implication follows directly. Treat the cache as an optimization, never a source of truth. Losing the cached weights means re-downloading them, and re-downloading is an inconvenience — it should never be a broken feature, because the feature's correctness must never depend on the cache surviving.

One cost is worth stating without euphemism: browsers do not share cached weights across origins. Two sites using the exact same public model each store their own separate copy. A Cross-Origin Storage API has been proposed (a WICG explainer) and can be tried through a Chrome extension that Transformers.js and WebLLM support as experimental options, but as of November 2026 the explainer states it is not yet natively implemented in browsers. That duplication is an honest cost of the library route, one the built-in-API route (in Chrome, for example) sidesteps because the browser downloads and manages the model itself — on devices that meet the browser's hardware and storage requirements. It is a genuine trade-off rather than a defect — the isolation that keeps one origin's cache invisible to another is the same isolation that keeps a hostile site from reading what a user has already downloaded elsewhere.

Versioning and invalidation

A selected model is a pinned dependency, and the cache key that stores it needs to carry that pin. Using "latest" as a cache key is exactly how two users end up silently running two different models without either of them, or the team, noticing — the failure is invisible until behavior diverges and nobody can explain why.

Model upgrades deserve deliberate handling as an event, not an incidental side effect of a deploy. The new version downloads alongside the old one, the swap happens atomically once the new version is fully present, and the old version is cleaned up afterward. Designing this way removes mid-session swaps and half-updated states as possibilities rather than trying to handle them gracefully after the fact.

js
// Cache key carries the exact pinned revision, never "latest"
const cacheKey = `model-v${MODEL_REVISION}`
const cached = await caches.match(cacheKey)
if (!cached) {
  const response = await fetch(MODEL_URL)
  if (!response.ok) throw new Error(`Model download failed: ${response.status}`)
  const cache = await caches.open('model-store')
  await cache.put(cacheKey, response)
}

The quantized-variant ladder from the selection side of this topic needs its own invalidation discipline. A device that moves up a rung — a new browser version, more available memory — may warrant the heavier artifact than it received before. Re-evaluating that fit belongs on the capability probe's own cadence, not on every single load, which would waste the very caching this article exists to make work.

First-run economics

The honest ledger has two very different rows. The first run pays for the download plus initialization; every repeat run after that skips the download but still pays the initialization cost described below. Whether a feature's economics work at all often comes down to how many sessions are available to amortize that one expensive first cost.

Initialization is not free even once the weights are safely cached. Loading weights into memory and warming up the inference runtime both take real, measurable time on real devices — and that cost must be measured on cold starts and warm starts separately, on median hardware, not on the development machine where everything is already fast.

A feature used only occasionally cannot justify holding a 200 MB model resident in cache indefinitely. That retention arithmetic feeds directly back into the task-fit decision this topic's main guide owns — a feature whose usage frequency cannot amortize its first-run cost was likely the wrong candidate for client-side inference in the first place, and no amount of caching cleverness changes that underlying math.

Project Inquiry