skip to content

An in-browser Transformers.js text-classification widget freezes the page for 40 seconds on first load; how do you move the pipeline into a Web Worker?

level: middleimportance: must knowfreq 10%

answer

  1. the page thread also paints
  2. load once, reuse for every message
  3. store the promise, not the result
  4. forward progress events with postMessage
  5. post plain data back, not a Tensor

basics

~20 s

Create the pipeline inside a module Web Worker, keep the pipeline() promise in a lazy singleton, and forward progress events and results to the page with postMessage. Session creation and inference then run off the main thread.

solid answer

~40 s

The download itself is asynchronous; the freeze comes from building the ONNX Runtime session and running inference, which are CPU-heavy and, on the page's thread, compete with input and rendering. Move the whole pipeline into a worker file with a lazy singleton, `instance ??= pipeline(task, model, { progress_callback })`, that stores the promise, so messages arriving during the load share one load and one session. The `progress_callback` simply calls `self.postMessage(x)`, and the page renders a bar from the forwarded events. On each `message` the worker awaits the instance, runs it and posts back plain data: a classifier's `[{ label, score }]` array is fine, while a feature-extraction `Tensor` should go back as `.tolist()` or its `.data` array. The Cache API is available in workers, so caching works unchanged.

code

javascript · 24 lines
javascript
// worker.js, created by the page as a module worker
import { pipeline } from '@huggingface/transformers';

const MODEL = 'Xenova/distilbert-base-uncased-finetuned-sst-2-english';
let instance = null;

function getClassifier(progress_callback) {
  // Store the promise so messages during the load share one load.
  instance ??= pipeline('text-classification', MODEL, { progress_callback }).catch((err) => {
    instance = null; // let the next message retry
    throw err;
  });
  return instance;
}

self.addEventListener('message', async (event) => {
  try {
    const classifier = await getClassifier((info) => self.postMessage(info));
    const output = await classifier(event.data.text);
    self.postMessage({ status: 'complete', output });
  } catch (err) {
    self.postMessage({ status: 'error', message: String(err) });
  }
});

go deeper

for a junior

Know that heavy model work belongs in a Web Worker so the page stays responsive, and that the worker talks to the page with postMessage.

for a middle

Explain which load phases are CPU-bound, the promise-holding singleton, forwarding progress events, and posting plain data instead of a Tensor.

for a senior

Handle the failure paths: reset a rejected load, report errors to the UI, dispose a model before switching, and keep one long-lived worker per model.

for a principal

Decide where model work should live across features: one shared worker or one per model, loading on demand versus prefetching, and the memory budget on low-end devices.

## Why the page freezes A browser page has one **main thread**, and it does everything the user sees: running scripts, handling input, laying out and painting. A Transformers.js `pipeline()` call has three phases on first use: 1. **Download** the config, tokenizer and ONNX weight files. This uses `fetch` and is asynchronous, so on its own it does not block the page. 2. **Build the inference session** from the weight bytes. ONNX Runtime parses and prepares the graph, which is real CPU work. 3. **Run inference** for each input: tokenization, the model and post-processing. Phases 2 and 3 are why a widget "freezes for 40 seconds": the awaited Promises do not help, because the heavy stretches of work run on whichever thread called them. If that is the main thread, clicks and paints wait. The remedy is to give the model its own thread, a **Web Worker**. How workers are created, terminated and how their messages are costed is general browser-platform material; what matters here is what runs inside the worker. ## The worker-side pattern 1. **One module worker owns the model.** The page creates it once, for example `new Worker(new URL('./worker.js', import.meta.url), { type: 'module' })`, so the worker can `import { pipeline } from '@huggingface/transformers'`. 2. **A lazy singleton holds the pipeline Promise.** `instance ??= pipeline(...)` stores the Promise itself, not the awaited result. Two messages that arrive while the model is still loading both await the same Promise, so there is one load and one session. 3. **Progress is forwarded.** The `progress_callback` runs inside the worker, so it simply calls `self.postMessage(info)`; the events are plain objects and the page renders its bar from them. 4. **Each request is answered.** The `message` handler awaits the instance, runs it on `event.data`, and posts back a result tagged with an app-defined status such as `'complete'`. 5. **Failures are reported, and the singleton is reset.** If the load rejects, clearing `instance` lets the next message retry instead of rethrowing a cached failure forever. ## What crosses the boundary | Item | What to post | |---|---| | Loading events | the `progress_callback` object as is | | text-classification output | the `[{ label, score }]` array as is | | feature-extraction output | `output.tolist()` or `output.data` with `output.dims` | | errors | an app-defined status plus `String(err)` | A `Tensor` is a class whose `data` and `dims` are getters over an internal runtime tensor; posted as is, it does not arrive on the page as a usable `Tensor`. Send plain arrays or typed arrays instead. ## What does and does not change inside a worker - **Caching still works.** The Cache API exists on the worker's global scope, so downloaded files go to the same per-origin store the page would use, and a second visit is still fast. - **The singleton lives as long as the worker.** Keep one long-lived worker per model rather than one per request; otherwise every request pays for a new session. - **Switching models needs cleanup.** A pipeline has an async `dispose()` that releases its model sessions; await it before loading a different model in the same worker. - **Load on demand.** The worker can delay `pipeline()` until the first message, so the download starts when the user actually needs the feature. ## The page side The page keeps a single reference to the worker, created once, for example in a component's mount effect, and attaches one `message` listener. That listener switches on `event.data.status`: the library's own `initiate`, `progress_total` and `ready` events drive the loading UI, while the app-defined `complete` and `error` statuses deliver results. To classify text, the page posts `{ text }` and waits for the reply. Nothing on the page imports `@huggingface/transformers`, so the library and the model stay out of the main bundle and off the main thread. ## Where this question stops Choosing a WebGPU or WASM device and tuning the WebAssembly backend are execution-backend settings. Worker lifecycle and the per-message copying cost belong to the browser-platform material on workers and messaging. This answer covers keeping the model's load and inference inside the worker.

  • What goes wrong if the worker's singleton stores the awaited pipeline instead of the Promise?
    Until the first load finishes the field is still `null`, so every message that arrives in the meantime calls `pipeline()` again. Each call builds its own session, doubling memory and CPU, and files may be fetched more than once. Storing the Promise makes all early callers await the same load.
  • With `instance ??= pipeline(...)`, what happens on the next message if the first load failed, for example because the network dropped?
    The rejected Promise stays in `instance`, so every later message awaits it and fails again without retrying. Attach a `.catch` that resets `instance` to `null` and rethrows, and post an error status to the page so the UI can offer a retry.
  • How do you switch a Transformers.js worker to a different model without keeping the first one in memory?
    Await the current instance, call `await pipe.dispose()` to release its model sessions, set the singleton back to `null`, then load the new model. Without `dispose()` the old sessions stay allocated in the worker for as long as anything references them.

  • Downloading the model is what blocks the main thread
  • An awaited pipeline() call cannot freeze the page
  • Each message should call pipeline() again to get a fresh pipeline
  • The Cache API is missing in workers, so the model re-downloads
  • A Tensor posted from the worker arrives on the page as a usable Tensor