Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 38 ยท Patterns and Tooling

Bundlers and Loading Strategies for WebAssembly

Learn how to load WebAssembly in real apps - fetch and instantiateStreaming, MIME types, Vite and Webpack imports, lazy loading, caching, Web Workers and fallbacks - with runnable loader examples.

You have a .wasm file. How does it get from your server to a running instance in the user's browser, and how do you make that path fast, cacheable and robust? The loading code is a small part of the project, yet it determines the startup time of everything built on top. Mistakes here (wrong MIME type, loading eagerly, compiling twice) cost real seconds.

This lesson covers the loading APIs, how bundlers treat .wasm files, and patterns for lazy loading, caching, workers and fallbacks. The runnable examples use the same WebAssembly and Response APIs that browsers provide, so the code carries over directly.

The loading APIs

API Input Notes
new WebAssembly.Module(bytes) ArrayBuffer or typed array Synchronous. Blocks the thread; browsers limit it on the main thread for big modules
WebAssembly.compile(bytes) bytes Async; returns a Module
WebAssembly.instantiate(bytes, imports) bytes Async; returns { module, instance }
WebAssembly.instantiate(module, imports) a Module Returns just an Instance; reuse one module many times
WebAssembly.compileStreaming(response) Response or a promise for one Compiles while downloading
WebAssembly.instantiateStreaming(response, imports) Response or promise The best default for a normal page

The streaming versions require the HTTP response to have the header Content-Type: application/wasm. They start compiling the first bytes while the rest are still arriving, so on a large module the compile time mostly hides behind the download.

JavaScript
// The standard pattern in a page
const { instance } = await WebAssembly.instantiateStreaming(
  fetch('/assets/engine.wasm'),
  { env: { log: (n) => console.log(n) } }
);
instance.exports.run();

A fast load path

Right MIME type application/wasm enables streaming.
Compression Brotli or gzip on the server.
Hashed file name Cache forever, bust by name.
Lazy load Fetch only when needed.

Compile while downloading.

1 / 2

The MIME type matters

If the server sends .wasm as application/octet-stream or text/plain, instantiateStreaming rejects with a TypeError. The code below simulates a server with Response objects, so you can see both outcomes and the standard fallback that many libraries include:

Node.js Streaming needs application/wasm

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The fallback works but loses the overlap between download and compile. The proper fix is configuring the server (application/wasm is registered with IANA, and nginx, Apache, Caddy and every CDN support it). Treat the fallback as a safety net, and log when it triggers so you notice a misconfiguration.

Lazy loading and caching one compiled module

Two rules keep startup fast. Do not fetch a module until the feature needs it, and never compile the same module twice. A loader function that caches a promise handles both, including the case where several parts of the page ask at the same moment:

Node.js A memoized lazy loader

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Caching the promise, not the result, is the key trick: it deduplicates concurrent calls. Real code often adds an IntersectionObserver or a click handler to trigger getModule() only when the feature becomes relevant, and <link rel="preload" as="fetch" type="application/wasm" crossorigin href="/engine.wasm"> to start the download early when you know it will be needed.

HTTP caching

A .wasm file rarely changes between deploys. Give it a content hash in the file name (engine.3f9a1c.wasm) and serve it with Cache-Control: public, max-age=31536000, immutable. Browsers also keep compiled code in a cache keyed by the response, so a repeat visit can skip compilation entirely. Do not rename or re-encode the file at the CDN, because that changes the bytes and defeats the code cache.

Bundlers

A bundler's job is to follow import statements and emit files. A .wasm file is not JavaScript, so each tool has its own convention.

Vite treats the .wasm as an asset. Importing it with ?url gives its final URL, which you pass to fetch. Recent Vite versions also support ?init, which returns an initializer function:

JavaScript
// Option A: the URL
import wasmUrl from './engine.wasm?url';
const { instance } = await WebAssembly.instantiateStreaming(fetch(wasmUrl), imports);

// Option B: ?init gives a function that instantiates for you
import init from './engine.wasm?init';
const instance = await init(imports);

Webpack 5 can import WebAssembly through its asyncWebAssembly experiment, so import { add } from './add.wasm' works inside async code:

JavaScript
// webpack.config.js
module.exports = { experiments: { asyncWebAssembly: true } };

Rust projects built with wasm-pack --target bundler produce a package whose package.json bundlers understand; --target web produces a file you load yourself.

Other tools (Rollup, esbuild, Parcel) usually need a plugin or a plain asset copy: treat the .wasm as a file, emit it with a hash, and write the URL into your loader.

General rules: keep the module as a separate file rather than inlining it as base64 into your JavaScript (base64 is a third bigger and cannot be streamed, compressed well or cached separately), except for tiny modules where saving a request is worth it.

Workers: keep the main thread free

Compiling and running heavy Wasm on the main thread freezes the page. A Web Worker gets its own thread:

JavaScript
// main.js
const worker = new Worker(new URL('./wasm-worker.js', import.meta.url), { type: 'module' });
worker.postMessage({ cmd: 'process', pixels: buffer }, [buffer]);   // transfer, do not copy
worker.onmessage = (e) => draw(e.data);

// wasm-worker.js
const { instance } = await WebAssembly.instantiateStreaming(fetch(wasmUrl), imports);
self.onmessage = ({ data }) => {
  const result = run(instance, data);
  self.postMessage(result, [result.buffer]);
};

A compiled WebAssembly.Module can itself be sent to a worker with postMessage, so several workers can instantiate it without each downloading and compiling it. This is the foundation of a worker pool (see also SIMD and Threads).

Feature fallbacks

Serve the best build the browser supports. Probe once at startup (see Other Languages for WebAssembly) and choose among engine-simd-threads.wasm, engine-simd.wasm and engine-baseline.wasm. Always test the baseline path: it is the one that quietly breaks.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does WebAssembly.instantiateStreaming sometimes reject with a TypeError?

    Streaming APIs require the wasm MIME type. Without it you must fall back to arrayBuffer() and instantiate.
  2. 2. Why cache the promise of a compiled module rather than the module itself?

    If two callers check a cache that is still empty, both would start compiling. A shared promise deduplicates them.
  3. 3. What is the best cache policy for a hashed engine.3f9a1c.wasm file?

    A new build gets a new hash, so the old URL can safely be cached for a year.
  4. 4. How do you pass a large ArrayBuffer to a worker without copying it?

    Transferring moves ownership of the buffer to the worker, which is instant regardless of size.

Summary

  • Prefer WebAssembly.instantiateStreaming(fetch(url)) with Content-Type: application/wasm; fall back to arrayBuffer() if needed.
  • Compile once, instantiate many times; cache the promise of the module and load lazily.
  • Hash file names, cache them for a year, serve Brotli, and do not modify the bytes in transit.
  • Bundlers treat .wasm as an asset (Vite ?url and ?init) or an async import (Webpack experiment); keep it a separate file.
  • Run heavy modules in workers, transfer buffers, and ship baseline fallbacks for newer features.

Next: Plugin Systems with WebAssembly