FE·29
PWAs, Workers & WebAssembly
Making web apps installable, offline-capable and fast: service worker lifecycle and caching strategies, background sync, push, IndexedDB, the web app manifest, worker messaging and transferables, and WebAssembly from C, C++, Rust, Zig and Go, including the JS/Wasm boundary.
Start here: apps that work offline, in parallel, and in any language
Three gaps between web pages and native apps
A classic web page needs the network to open, does all its work on one thread, and runs only JavaScript. Three platform features close those gaps:
| Gap | Feature | Analogy |
|---|---|---|
| "It doesn't work offline, and it isn't an app on my phone" | Service workers and the web app manifest → a PWA (progressive web app) | a receptionist who answers the door even when the office is closed |
| "Heavy work freezes the page" | Web Workers | an assistant working in another room, passing notes |
| "We already have this in C++/Rust", "JavaScript is too slow for this" | WebAssembly (Wasm) | a compact, portable machine language the browser runs safely |
Service workers: a programmable proxy in the browser
A service worker is a JavaScript file that the browser installs for your site and runs between your pages and the network. Every request your pages make (for HTML, scripts, images, API data) passes through its fetch event, where your code decides: answer from a cache, go to the network, or both. It keeps working when there's no connection, and even when no tab of your site is open (for push messages and background sync).
// sw.js
self.addEventListener("install", e =>
e.waitUntil(caches.open("shell-v1").then(c => c.addAll(["/", "/app.js", "/style.css"])))); // save the app shell
self.addEventListener("fetch", e => {
const url = new URL(e.request.url);
if (url.pathname.startsWith("/api/")) { // data: network first, fall back to the last saved copy
e.respondWith(fetch(e.request)
.then(res => { const copy = res.clone(); caches.open("api").then(c => c.put(e.request, copy)); return res; })
.catch(() => caches.match(e.request)));
} else { // the app shell: cache first
e.respondWith(caches.match(e.request).then(r => r || fetch(e.request)));
}
});
// in the page
navigator.serviceWorker.register("/sw.js");
With that in place, a menu app visited twice and then opened with the network switched off:
1st visit (online): {"dishes":["Masala dosa","Idli"],"version":1} | controlled by a service worker: true
2nd visit (online): {"dishes":["Masala dosa","Idli"],"version":2}
3rd visit (OFFLINE): {"dishes":["Masala dosa","Idli"],"version":2} | page title: Tiffin
a new tab while offline: loaded | heading: Today's menu
Offline, the page still loaded (the shell came from the cache) and showed the last menu it had seen (version 2), instead of the browser's "No internet" page. Service workers only work on HTTPS (or localhost), because something that can intercept every request must not be injectable by a network attacker.
Installable apps: the manifest
A web app manifest is a small JSON file describing the app: its name, icons, colours, and how it should open ("display": "standalone" hides the browser UI). With a manifest (name, icons, start_url, display mode) served over HTTPS, browsers offer Install (Chromium has dropped its old requirement for a service worker, though you'll want one for offline support), and the site gets a home-screen icon, its own window and an entry in the app switcher. The test app's manifest passed Chromium's installability check with no errors:
{ "name": "Sharma's Tiffin", "short_name": "Tiffin", "start_url": "/", "display": "standalone",
"background_color": "#ffffff", "theme_color": "#8a4b08",
"icons": [{ "src": "/icon-192.png", "sizes": "192x192", "type": "image/png" },
{ "src": "/icon-512.png", "sizes": "512x512", "type": "image/png" }] }
Web Workers: real parallelism
The page's main thread runs your JavaScript and renders frames (chapter 18), so a long calculation freezes everything. A Web Worker runs a script on a separate thread. It has no access to the DOM; it communicates with the page by messages:
// worker.js
onmessage = e => { const result = expensiveCalculation(e.data); postMessage(result); };
// page
const worker = new Worker("/worker.js");
worker.onmessage = e => showResult(e.data);
worker.postMessage({ w: 1600, h: 1200, maxIter: 500 });
The same 0.7-second calculation (a Mandelbrot image), with a spinning animation on the page, counting the frames the browser managed to paint:
same work on the main thread: 732 ms, 8 frames painted (11 fps)
same work in a Web Worker: 720 ms, 43 frames painted (60 fps)
The work took the same time; the difference is that the page stayed smooth and responsive while it ran. Messages are copied (chapter 12's structured clone), so sending large data is expensive, unless you transfer it: sending a 100 MB buffer took 659 ms as a copy and 1.8 ms as a transfer (the lab explains why).
WebAssembly: other languages in the browser
WebAssembly is a compact binary instruction format, designed as a compilation target: C, C++, Rust, Zig, Go, C#, Kotlin and others compile to it, and every browser runs it in the same sandbox as JavaScript, at near-native speed. A C function compiled with clang --target=wasm32 produced a 571-byte .wasm file, loaded like this:
const { instance } = await WebAssembly.instantiateStreaming(fetch("/mandel.wasm"));
const total = instance.exports.mandel(800, 600, 500); // call the exported C function from JavaScript
Wasm doesn't replace JavaScript; it complements it. JavaScript still owns the DOM and the page; Wasm modules export functions that JavaScript calls for heavy, self-contained work. Real uses include Figma's rendering engine (C++), Photoshop and AutoCAD on the web, Google Earth, SQLite in the browser, video and image codecs, PDF rendering, games, and running Python (Pyodide) or a whole Linux shell in a tab. Is it faster than JavaScript? Sometimes much, sometimes not at all: the lab measures both cases.
How deep to go in PWAs, workers and WebAssembly
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain service workers, the manifest, Web Workers and WebAssembly |
| L2 | Add offline support and installability; move heavy work to a worker; call a Wasm module |
| L3 | Explain the service worker lifecycle and update flow, caching strategies, structured clone vs transfer, Wasm memory and the JS boundary |
| L4 | Diagnose stale service workers, cache bloat, worker message bottlenecks and slow JS/Wasm boundaries |
| L5 | Design offline-first data sync, worker architecture (pools, Comlink, OffscreenCanvas) and Wasm module boundaries |
| L6 | Operate PWAs and Wasm at scale: update rollouts, storage quotas, cross-browser gaps (iOS), Wasm toolchains and size budgets |
Progressive web apps
What a PWA is
A progressive web app is a website that uses modern web capabilities to behave like an installed app: it works offline or on flaky networks, can be installed to the home screen or desktop with its own window, can receive push notifications, and loads instantly on repeat visits. "Progressive" means it works as a normal website everywhere and enhances where the browser supports more. Three ingredients are needed:
- HTTPS (a secure context, chapter 12).
- A service worker for network control and offline support.
- A web app manifest for installability and app metadata.
PWAs are used by Starbucks, Twitter/X Lite, Pinterest, Spotify's web player, Google Workspace, and many e-commerce and media sites, particularly in markets with low-end devices and patchy networks. On iOS, home-screen web apps gained push notifications in 16.4. In the EU, policy has wavered on whether iOS home-screen apps open in full app mode.
Service workers in depth
A service worker is a JavaScript worker that the browser runs separately from your pages, acting as a programmable network proxy for every request from pages in its scope (chapter 17). Its lifecycle is the part that trips everyone up:
- Register from the page:
navigator.serviceWorker.register("/sw.js", { scope: "/" }). The browser downloadssw.js, and checks it for updates on navigations (at most once a day by default, or when you callregistration.update()). install: precache the app shell. If precaching fails, installation fails and the old worker stays.waiting: a new version waits while any tab still uses the old one, so a page never mixes old and new code.self.skipWaiting()activates immediately (risky if the old page's code expects old cache contents). Most apps instead show an "Update available, reload?" prompt.activate: delete caches from old versions.clients.claim()takes control of already-open pages.- Controlling: handles
fetch,push,sync,notificationclickandmessageevents. The browser terminates idle workers (after about 30 seconds) and restarts them for each event, so don't keep state in global variables. Use IndexedDB or Cache Storage.
// sw.js
const VERSION = "v42";
const SHELL = `shell-${VERSION}`;
const RUNTIME = "runtime";
const SHELL_ASSETS = ["/", "/offline.html", "/app.3f9a1c.js", "/app.8b2e.css", "/icons/192.png"];
self.addEventListener("install", (e) => {
e.waitUntil(caches.open(SHELL).then((c) => c.addAll(SHELL_ASSETS))); // waitUntil extends the event's lifetime
});
self.addEventListener("activate", (e) => {
e.waitUntil((async () => {
for (const key of await caches.keys()) if (key.startsWith("shell-") && key !== SHELL) await caches.delete(key);
await self.clients.claim();
})());
});
self.addEventListener("fetch", (e) => {
const url = new URL(e.request.url);
if (e.request.method !== "GET" || url.origin !== location.origin) return; // let the network handle it
if (e.request.mode === "navigate") e.respondWith(networkFirst(e.request)); // HTML pages
else if (url.pathname.startsWith("/api/")) e.respondWith(staleWhileRevalidate(e.request));
else e.respondWith(cacheFirst(e.request)); // hashed static assets
});
Offline caching strategies
Choose a strategy per kind of request:
| Strategy | Behaviour | Use for |
|---|---|---|
| Cache first (cache, falling back to network) | Serve from cache; fetch and store on miss | Content-hashed static assets, fonts, icons: they never change at a given URL |
| Network first (network, falling back to cache) | Try the network with a timeout; on failure, serve cached; for navigations, an offline page | HTML navigations, frequently updated content where freshness matters |
| Stale-while-revalidate | Serve cached immediately, update the cache from the network in the background | Avatars, non-critical API data, feeds where slightly stale is fine |
| Network only | Never cache | Payments, auth, analytics POSTs |
| Cache only | Precached content only | The app shell in a fully offline app |
async function cacheFirst(req) {
const cached = await caches.match(req);
if (cached) return cached;
const res = await fetch(req);
if (res.ok) (await caches.open(RUNTIME)).put(req, res.clone()); // a body can be read once: clone (chapter 17)
return res;
}
async function networkFirst(req) {
try {
const res = await fetch(req, { signal: AbortSignal.timeout(4000) });
(await caches.open(RUNTIME)).put(req, res.clone());
return res;
} catch {
return (await caches.match(req)) ?? (await caches.match("/offline.html"));
}
}
async function staleWhileRevalidate(req) {
const cache = await caches.open(RUNTIME);
const cached = await cache.match(req);
const network = fetch(req).then((res) => { if (res.ok) cache.put(req, res.clone()); return res; }).catch(() => cached);
return cached ?? network;
}
In practice, use Workbox (Google's service-worker library), or framework integrations (vite-plugin-pwa, @angular/pwa with ngsw-config.json, Serwist for Next.js). They generate precache manifests with content hashes, implement these strategies with expiration (max entries and max age), and handle updates. Hand-written service workers are a common source of "users stuck on an old version" bugs.
Pitfalls:
- Never cache-first your HTML without a version strategy: users get stuck on old shells pointing at deleted assets.
- Don't cache authenticated API responses in shared runtime caches without scoping them per user, and clear them on logout.
- Opaque responses (cross-origin
no-cors) can't be inspected, and Chrome counts them as about 7 MB each against your quota. - Always ship a kill switch: a no-op service worker you can deploy at the same URL that unregisters itself, in case a bad version ships.
Background sync
Background Sync lets a page defer an action until the device has connectivity, even if the user closes the tab:
// page: queue the action locally, then ask for a sync
await db.put("outbox", { id: crypto.randomUUID(), type: "comment", body: text }); // IndexedDB outbox
const reg = await navigator.serviceWorker.ready;
await reg.sync?.register("flush-outbox"); // Chromium only
// sw.js
self.addEventListener("sync", (e) => {
if (e.tag === "flush-outbox") e.waitUntil(flushOutbox()); // retried by the browser with backoff if it fails
});
async function flushOutbox() {
for (const item of await db.getAll("outbox")) {
const res = await fetch("/api/comments", {
method: "POST",
headers: { "Content-Type": "application/json", "Idempotency-Key": item.id }, // safe to retry
body: JSON.stringify(item),
});
if (res.ok) await db.delete("outbox", item.id);
}
}
Support is Chromium-only, and Periodic Background Sync (refresh content on a schedule) is limited to installed apps with engagement. The portable pattern is an outbox in IndexedDB, flushed on online events, page load and visibility changes, with background sync as an enhancement. Idempotency keys (chapter 25) make retries safe. Workbox's BackgroundSyncPlugin implements this.
Push notifications
Web Push delivers messages from your server to the user's device even when the site is closed:
- The page asks for notification permission (after a user gesture, chapter 17), then subscribes:
registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: VAPID_PUBLIC_KEY }). - The browser returns a subscription (an endpoint URL at the browser vendor's push service, plus encryption keys). Send it to your server and store it per user and device.
- To notify, your server sends an encrypted message (RFC 8291) to the endpoint, signed with your VAPID private key (RFC 8292). Libraries:
web-push(Node),webpush-java,webpush-go,web-push(Rust). - The push service wakes your service worker, which must show a notification (
userVisibleOnly: no silent tracking pushes).
self.addEventListener("push", (e) => {
const data = e.data?.json() ?? {};
e.waitUntil(self.registration.showNotification(data.title ?? "Update", {
body: data.body, icon: "/icons/192.png", badge: "/icons/badge.png",
data: { url: data.url }, tag: data.tag, // tag replaces older notifications of the same kind
}));
});
self.addEventListener("notificationclick", (e) => {
e.notification.close();
e.waitUntil(clients.openWindow(e.notification.data.url ?? "/"));
});
Handle expired subscriptions (a 404 or 410 from the push service means delete the subscription), let users manage preferences, and keep notifications relevant. Users revoke permission quickly when they get spam.
IndexedDB for offline data
Offline apps need data, not just the shell. IndexedDB (chapter 17) is the client-side database:
- Read-through caching of server data (TanStack Query's persisters can persist the query cache to IndexedDB).
- Outbox for writes made offline (above).
- Full local-first storage with sync engines (chapter 25).
- Large blobs: offline media and documents. Request persistent storage (
navigator.storage.persist()) so the browser doesn't evict them.
Plan for schema migrations (IndexedDB versions), storage eviction (handle QuotaExceededError), and conflict resolution when offline edits sync: last-write-wins, server-authoritative merge, or CRDTs.
Installability and the web app manifest
The web app manifest is a JSON file linked from your HTML. It tells the browser how to present your app when installed:
{
"name": "Shop: Socks & More",
"short_name": "Shop",
"id": "/?source=pwa",
"start_url": "/?source=pwa",
"scope": "/",
"display": "standalone",
"display_override": ["window-controls-overlay", "standalone"],
"background_color": "#ffffff",
"theme_color": "#0d6e69",
"icons": [
{ "src": "/icons/192.png", "sizes": "192x192", "type": "image/png" },
{ "src": "/icons/512.png", "sizes": "512x512", "type": "image/png" },
{ "src": "/icons/maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }
],
"shortcuts": [{ "name": "My orders", "url": "/orders", "icons": [{ "src": "/icons/orders.png", "sizes": "96x96" }] }],
"screenshots": [{ "src": "/screens/home.png", "sizes": "1080x1920", "type": "image/png", "form_factor": "narrow" }],
"share_target": { "action": "/share", "method": "POST", "enctype": "multipart/form-data", "params": { "files": [{ "name": "photo", "accept": ["image/*"] }] } }
}
<link rel="manifest" href="/manifest.webmanifest">
Installability criteria (Chromium): HTTPS, a manifest with a name, icons (192 and 512 px), start_url and display, plus (historically) a service worker with a fetch handler. You can capture the beforeinstallprompt event to show your own "Install app" button at a sensible moment. Safari users install with Share → Add to Home Screen. display modes: fullscreen, standalone (an app window without browser UI), minimal-ui and browser. Detect installed mode with matchMedia("(display-mode: standalone)").
Installed PWAs can use more OS integration: badging (navigator.setAppBadge(3)), share targets, file handlers and protocol handlers (desktop Chromium), window controls overlay, and app shortcuts. Desktop PWAs can be published to the Microsoft Store and, through Trusted Web Activities, to Google Play.
Workers
Worker messaging
Chapter 17 introduced workers. Communication is message passing, using the actor/CSP model (Vol. 1 ch. 2):
// Request/response over postMessage with IDs (what Comlink automates)
const pending = new Map();
let nextId = 0;
worker.onmessage = ({ data }) => { pending.get(data.id)?.(data.result); pending.delete(data.id); };
function call(method, args) {
const id = nextId++;
return new Promise((resolve) => { pending.set(id, resolve); worker.postMessage({ id, method, args }); });
}
// MessageChannel: a dedicated two-way pipe (ports can be transferred to other workers or iframes)
const { port1, port2 } = new MessageChannel();
worker.postMessage({ type: "connect" }, [port2]); // hand one end to the worker
port1.onmessage = (e) => console.log("from worker:", e.data);
Design guidance:
- Keep messages coarse. Each message costs a structured clone and a task, so batch updates instead of sending one message per row.
- Keep data where the work happens. Load the dataset into the worker (fetch it there, or keep it in IndexedDB), and send queries and small results.
- Handle errors and cancellation: worker
errorevents,messageerror(failed deserialisation), and abort signals forwarded as messages. - Pool workers for parallel CPU work (
navigator.hardwareConcurrencygives the core count), the way Java'sForkJoinPoolor Rust's rayon do. Libraries like workerpool and threads.js help.
Transferable objects
Some objects can be transferred instead of copied. Ownership moves to the receiver in O(1), and the sender's reference becomes unusable (detached):
const buf = new ArrayBuffer(64 * 1024 * 1024); // 64 MB
worker.postMessage({ buf }, [buf]); // transfer list
buf.byteLength; // 0: detached in the sender, like a Rust move (Vol. 1 ch. 2)
// Transferable: ArrayBuffer, MessagePort, ImageBitmap, OffscreenCanvas, ReadableStream/WritableStream/TransformStream,
// VideoFrame, AudioData, RTCDataChannel, MediaStreamTrack (varies)
const offscreen = canvas.transferControlToOffscreen();
renderWorker.postMessage({ canvas: offscreen }, [offscreen]); // the worker now draws the canvas (WebGL/2D) off the main thread
structuredClone(value, { transfer: [buf] }) does the same within one thread. Transferring makes zero-copy pipelines possible: decode an image in a worker into an ImageBitmap, transfer it to the main thread, and draw it. It's the same ownership-transfer idea as Rust's Send or Go's "share memory by communicating".
SharedArrayBuffer goes further: both threads see the same memory at the same time, with Atomics (Atomics.add, compareExchange, wait/notify) providing the primitives of Vol. 1 ch. 8 (atomics, futex-like waits). It requires cross-origin isolation (COOP + COEP, chapter 28), and it's what multithreaded WebAssembly (pthreads in Emscripten, Rust's wasm-bindgen-rayon) builds on.
WebAssembly
What WebAssembly is
WebAssembly (Wasm, Vol. 1 ch. 10) is a portable, compact, sandboxed binary instruction format for a stack-based virtual machine. Browsers compile it to native machine code quickly (streaming compilation while downloading, then tiered optimisation), so it runs at near-native speed, often within 1.2–2× of native. It's a compilation target: you write C, C++, Rust, Zig, Go, C#, Kotlin, AssemblyScript and others, and ship .wasm.
Properties that matter:
- Sandboxed: a Wasm module can't touch anything outside its own linear memory (a growable
ArrayBuffer) except through functions the host explicitly imports into it. Out-of-bounds accesses trap instead of corrupting the host. A memory-unsafe C library is contained inside its own memory. - Predictable performance: no JIT warm-up cliffs, no GC pauses for linear-memory code, and SIMD (128-bit) and threads support.
- Same origin rules and permissions as JS: Wasm has no extra privileges. It reaches the web only through JS glue or imported functions.
Uses: image and video processing (Squoosh, Photoshop on the web), CAD and design tools (Figma's renderer is C++ compiled to Wasm; AutoCAD web), games and engines (Unity, Unreal, Godot), databases in the browser (SQLite-Wasm, DuckDB-Wasm, PGlite: Postgres in Wasm), codecs (ffmpeg.wasm), crypto, emulators, ML inference (ONNX Runtime Web, TensorFlow.js Wasm backend, with WebGPU for acceleration), and reusing existing native libraries on the web. Outside the browser: plugin systems, serverless and edge compute (WASI, Vol. 1 ch. 10).
The text format and the module structure
The binary has a readable text format (.wat):
(module
(func $add (export "add") (param $a i32) (param $b i32) (result i32)
local.get $a
local.get $b
i32.add)
(memory (export "memory") 1) ;; 1 page = 64 KiB of linear memory
)
const { instance } = await WebAssembly.instantiateStreaming(fetch("/add.wasm"), { /* imports */ });
instance.exports.add(2, 3); // 5
// Serve .wasm with Content-Type: application/wasm (needed for instantiateStreaming)
The core value types are only i32, i64, f32, f64 and v128 (SIMD), plus reference types. Everything else (strings, structs, arrays) lives as bytes in linear memory, which is why the boundary with JavaScript needs glue code. Recent standardised features: WasmGC (garbage-collected structs and arrays managed by the host's GC, which lets Kotlin, Dart, Java and OCaml compile efficiently without shipping their own GC), exception handling, tail calls, threads, SIMD, 64-bit memory (memory64), and relaxed SIMD. Wasm 3.0 (2025) bundled many of these. The Component Model and WASI 0.2/0.3 add a language-neutral interface type system (WIT) for composing modules written in different languages, mainly outside browsers.
Compiling C, C++, Rust, Zig and Go to Wasm
The same tiny function, compiled from five languages:
// Rust: wasm-bindgen + wasm-pack generate the JS glue and TypeScript types
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn blur(pixels: &mut [u8], width: u32, height: u32, radius: u32) {
// operate directly on the RGBA buffer passed from JS (a view into Wasm memory)
box_blur(pixels, width as usize, height as usize, radius as usize);
}
#[wasm_bindgen]
pub fn greet(name: &str) -> String { format!("Hello, {name}!") } // strings copied across (UTF-8 ↔ UTF-16)
// $ wasm-pack build --target web --release → pkg/ with .wasm, .js glue, .d.ts
// JS: import init, { blur, greet } from "./pkg/imagefx.js"; await init(); greet("Asha");
// C with Emscripten: emcc compiles via Clang/LLVM and emits JS glue
#include <emscripten/emscripten.h>
#include <stdint.h>
EMSCRIPTEN_KEEPALIVE
void blur(uint8_t *pixels, int width, int height, int radius) { /* … */ }
EMSCRIPTEN_KEEPALIVE
int add(int a, int b) { return a + b; }
// $ emcc fx.c -O3 -sEXPORTED_RUNTIME_METHODS=ccall,cwrap -sALLOW_MEMORY_GROWTH -o fx.js
// JS: const add = Module.cwrap("add", "number", ["number", "number"]);
// Emscripten also emulates POSIX (files, pthreads, SDL, OpenGL→WebGL) to port whole apps
// C++ with Emscripten embind: bind classes and std::string/vector with generated glue
#include <emscripten/bind.h>
#include <string>
using namespace emscripten;
class Histogram {
public:
explicit Histogram(int bins) : counts_(bins, 0) {}
void add(double v) { /* … */ }
std::vector<int> counts() const { return counts_; }
private:
std::vector<int> counts_;
};
EMSCRIPTEN_BINDINGS(stats) {
class_<Histogram>("Histogram").constructor<int>().function("add", &Histogram::add).function("counts", &Histogram::counts);
register_vector<int>("VectorInt");
}
// JS: const h = new Module.Histogram(10); h.add(3.2); … h.delete(); // manual free of C++ objects!
// Zig: a first-class wasm32 target, tiny output, explicit memory
const std = @import("std");
export fn add(a: i32, b: i32) i32 { return a + b; }
// Expose an allocator so JS can pass buffers in
export fn alloc(len: usize) ?[*]u8 {
const buf = std.heap.wasm_allocator.alloc(u8, len) catch return null;
return buf.ptr;
}
export fn free(ptr: [*]u8, len: usize) void { std.heap.wasm_allocator.free(ptr[0..len]); }
export fn blur(ptr: [*]u8, len: usize, width: u32, height: u32) void {
const pixels = ptr[0..len];
_ = pixels; _ = width; _ = height; // … process in place
}
// $ zig build-exe fx.zig -target wasm32-freestanding -fno-entry -rdynamic -O ReleaseSmall
// Go: GOOS=js GOARCH=wasm with syscall/js (or TinyGo for much smaller binaries)
package main
import "syscall/js"
func add(this js.Value, args []js.Value) any { return args[0].Int() + args[1].Int() }
func main() {
js.Global().Set("goAdd", js.FuncOf(add))
select {} // keep the Go runtime alive so callbacks keep working
}
// $ GOOS=js GOARCH=wasm go build -o main.wasm (+ wasm_exec.js glue from $(go env GOROOT)/lib/wasm)
// Standard Go ships its runtime + GC: binaries are ~2 MB+. TinyGo: often 10–100× smaller.
// GOOS=wasip1 targets WASI for server-side/edge use; Go 1.24 added go:wasmexport.
How the toolchains compare for web use:
| Toolchain | Glue | Typical size | Notes | |
|---|---|---|---|---|
| Rust | wasm-bindgen, wasm-pack, trunk; Leptos and Yew frameworks |
Generated JS + .d.ts |
Small (KB to hundreds of KB with opt-level="z", wasm-opt) |
Best web ecosystem; no GC needed; web-sys binds every Web API |
| C/C++ | Emscripten (LLVM) | Generated JS, POSIX emulation, embind | Varies; good for porting large codebases | Ports existing libraries (ffmpeg, SQLite, OpenCV, game engines) |
| Zig | Built-in wasm32 targets |
Hand-written (export functions) | Tiny | Excellent control; zig cc can also build C to Wasm |
| Go | GOOS=js, TinyGo |
wasm_exec.js |
Large (runtime + GC) / small with TinyGo | Easy for Go teams; heavy for the browser |
| Kotlin / Dart / Java (via WasmGC) | Kotlin/Wasm, Dart (Flutter web), J2Wasm/TeaVM | Generated | Medium | Uses the browser's GC |
| AssemblyScript | TS-like language → Wasm | Generated | Small | Familiar syntax for JS developers |
The JS/Wasm boundary
The boundary between JavaScript and Wasm is where performance is won or lost:
- Calls across the boundary are cheap (nanoseconds in modern engines), but data conversion isn't. Numbers pass directly. Strings must be encoded (UTF-16 JS ↔ UTF-8 linear memory:
TextEncoder/TextDecoder, chapter 15) and copied. Objects must be serialised or represented as handles. - Share memory instead of copying. JS can create a typed-array view directly over Wasm's linear memory (
new Uint8Array(instance.exports.memory.buffer, ptr, len)) and read or write it with zero copies. Allocate in Wasm (an exportedalloc), write the input in through the view, call the function, and read the output through a view. - Views go stale when memory grows.
memory.grow()replaces the underlyingArrayBuffer, detaching old views. Recreate views after any call that might allocate. - Design chunky APIs, not chatty ones: one call that processes a whole image, not one call per pixel. Crossing the boundary millions of times erases Wasm's advantage.
- Memory management across languages: objects allocated in Wasm (C++ classes through embind, Rust structs exported through
wasm-bindgen) aren't freed by JS's GC. Call.free()/.delete(), or rely onFinalizationRegistry-based cleanup (best-effort only, chapter 15). - The DOM is only reachable through JS. Wasm calls imported JS functions to touch the DOM. UI frameworks written in Rust (Leptos, Yew, Dioxus) do this through
web-sys. For DOM-heavy UI work, JS frameworks are usually faster overall because of the boundary costs. Wasm wins for compute-heavy kernels. - Async: Wasm functions are synchronous. Long computations should run in a Web Worker (Wasm works in workers) so the main thread stays responsive. JSPI (JavaScript Promise Integration) lets Wasm suspend on JS promises, which helps port synchronous C code that does I/O.
// Zero-copy pattern with the Zig module above
const { instance } = await WebAssembly.instantiateStreaming(fetch("/fx.wasm"));
const { memory, alloc, free, blur } = instance.exports;
const img = ctx.getImageData(0, 0, w, h); // RGBA bytes from a canvas
const ptr = alloc(img.data.length);
new Uint8Array(memory.buffer, ptr, img.data.length).set(img.data); // copy in once
blur(ptr, img.data.length, w, h); // process in place inside Wasm
img.data.set(new Uint8Array(memory.buffer, ptr, img.data.length)); // fresh view (memory may have grown)
ctx.putImageData(img, 0, 0);
free(ptr, img.data.length);
When to use WebAssembly
| Use Wasm when… | Stick with JS when… |
|---|---|
| CPU-heavy computation dominates (codecs, image/audio processing, physics, compression, crypto, parsing huge files, simulations) | The work is mostly DOM manipulation and UI |
| You want to reuse an existing native library (C/C++/Rust) instead of rewriting it | The JS ecosystem already has a good solution |
| You need predictable performance without GC pauses or JIT deoptimisation | Bundle size and startup matter more than raw speed (a Wasm module + glue is a download too) |
| You share code between server and client (Rust logic in a Rust backend and in the browser) | Your team doesn't know the source language |
Measure first. Modern JS JITs are very fast for typical code. Wasm typically wins by 1.5–20× on tight numeric loops, SIMD-friendly kernels, and code that would otherwise trigger JIT deoptimisations, and it can lose when the boundary is crossed too often.
Lab: offline, parallel and compiled, measured
Experiments in Chromium 153 via Playwright; the WebAssembly modules were compiled from C with Clang 18 (clang --target=wasm32 -O2 -nostdlib -Wl,--no-entry), producing modules of 571 bytes and a few kilobytes with no runtime or libc.
Experiment 1: a service worker through three visits
The Start here results came from this sequence: visit online (the service worker installs and caches the shell), reload online (pages are now served through it; the API is fetched fresh, version 2), then switch the browser context offline with Playwright's context.setOffline(true) and reload, then open a brand-new tab:
1st visit (online): {"dishes":["Masala dosa","Idli"],"version":1} | controlled by a service worker: true
2nd visit (online): {"dishes":["Masala dosa","Idli"],"version":2}
3rd visit (OFFLINE): {"dishes":["Masala dosa","Idli"],"version":2} | page title: Tiffin
a new tab while offline: loaded | heading: Today's menu
installability errors: []
Two points the output hides. First, on the very first visit the page wasn't controlled until the service worker called clients.claim() in its activate event; without it, only the next navigation is controlled, which confuses many first implementations. Second, updates: when you deploy a new sw.js, the browser installs it alongside the old one and, by default, waits until every tab using the old version is closed before activating it. Apps either call skipWaiting() (risky: old pages suddenly talk to a new worker) or show "A new version is available, reload?" when the new worker is waiting. Bump the cache name (shell-v2) and delete old caches in activate, or users keep stale files forever. Libraries such as Workbox generate this correctly from your build output.
Experiment 2: keeping the page responsive with a worker
A spinning element animated on the page while a 1600 × 1200 Mandelbrot calculation (500 iterations) ran; requestAnimationFrame counted the frames the browser actually painted:
same 1600×1200 Mandelbrot on the main thread: 732 ms, 8 frames painted (11 fps)
same work in a Web Worker: 720 ms, 43 frames painted (60 fps)
On the main thread, the page froze for the whole calculation: the only frames painted were in the 50 ms pauses before and after. In a worker, the main thread kept a full 60 fps (and would have handled clicks immediately). Workers cost a few megabytes and some start-up time each, so create them once and reuse them (a small pool sized to navigator.hardwareConcurrency); libraries such as Comlink make a worker look like an async object (await api.mandel(job)).
Experiment 3: copying versus transferring data
Sending a 100 MB ArrayBuffer to a worker, measuring how long postMessage blocked the sender:
worker.postMessage(big1); // structured clone: copy every byte
worker.postMessage(big2, [big2]); // transfer: hand over ownership
copy 659.2 ms (sender still has 100 MB) | transfer 1.80 ms (sender's buffer is now 0 bytes)
Copying 100 MB blocked the main thread for two-thirds of a second, which defeats the point of using a worker. Transferring moved the memory to the worker without copying; the price is that the sender's buffer is detached (byteLength 0) and can't be used any more. ArrayBuffers, MessagePorts, ImageBitmaps, OffscreenCanvases and streams are transferable. SharedArrayBuffer goes further, letting both threads see the same memory (with Atomics for synchronisation), but requires cross-origin isolation (COOP + COEP headers, chapter 28) because shared memory enables precise timers for Spectre-style attacks.
Experiment 4: when WebAssembly is faster, and when it isn't
The same Mandelbrot kernel written in JavaScript and in C compiled to Wasm, medians of five runs after warm-up:
Mandelbrot 800×600, 500 iterations: JS 149 ms (result 53023321) | Wasm 148 ms (result 53023321)
10 million calls of add(): from JS to Wasm 28 ms | JS to JS 5 ms
For floating-point loops over local variables, V8's optimising compiler (chapter 18) produces machine code as good as Clang's, so Wasm gained nothing. And calling a tiny Wasm function 10 million times was 5.6× slower than calling a JavaScript function, because each call crosses the JS/Wasm boundary and can't be inlined. Now a task that suits Wasm: a 64-bit FNV-1a hash of 4 MB of data. JavaScript numbers are 64-bit floats, so 64-bit integer multiplication needs BigInt or manual tricks:
FNV-1a 64-bit hash of 4 MB: JS with BigInt ≈ 146 ms (extrapolated) | JS with 16-bit limbs 13 ms | Wasm (incl. copying the data in) 9 ms | all agree: true
Wasm's native i64 multiply beat clean BigInt code by about 16×, and still beat the hand-optimised JavaScript that splits each 64-bit value into four 16-bit pieces (code few people would write or maintain). The pattern holds generally: Wasm wins on 64-bit integer math, SIMD, predictable performance without JIT warm-up or deoptimisation, and reusing native libraries; it doesn't help DOM-heavy code or chatty calls across the boundary. Design Wasm modules with coarse interfaces: pass a whole buffer, get a whole result.
Try it yourself
- Change experiment 1's
sw.js(bump the cache toshell-v2) while a tab is open. Watch DevTools → Application → Service workers show the new worker "waiting to activate". Add an "update available" banner. - Rewrite experiment 2 with an
OffscreenCanvastransferred to the worker, so the worker draws the Mandelbrot image directly. - Compile the Mandelbrot kernel from Rust (
wasm32-unknown-unknown) or Zig (-target wasm32-freestanding) and compare file sizes and speed with the C version. - Enable SIMD in the C build (
-msimd128) and vectorise the FNV loop over four independent streams. How much faster is it?
Revision sheet: PWAs, workers and WebAssembly
Key ideas
- Service workers: register → install (precache) → wait → activate (claim, clean old caches) → fetch/push/sync events; scope by path; HTTPS only; updates wait for old clients unless
skipWaiting(). - Caching strategies: cache first (versioned assets), network first (fresh data with offline fallback), stale-while-revalidate (fast and eventually fresh), network only, cache only; navigation preload; offline fallback pages.
- Offline data: IndexedDB as the local database; background sync to retry writes; conflict handling.
- Push: Push API + Notifications via the service worker; permission UX; iOS supports web push for installed PWAs.
- Manifest and install: name, icons,
start_url,display, theme colours, shortcuts, share target; installability prompts differ by browser. - Web Workers: dedicated and shared workers; message passing with structured clone; transferables;
SharedArrayBuffer+Atomicswith cross-origin isolation;OffscreenCanvas; worker pools; Comlink. - WebAssembly: stack-machine bytecode with linear memory; imports and exports; toolchains (Emscripten, wasm-bindgen/wasm-pack, Zig, TinyGo/Go, .NET, Kotlin/Wasm with WasmGC); WASI outside the browser; SIMD, threads, exception handling and GC proposals.
Numbers to remember
- Lab: main-thread work 11 fps vs worker 60 fps; copying 100 MB 659 ms vs transferring 1.8 ms.
- Lab: Mandelbrot JS 149 ms ≈ Wasm 148 ms; 10M boundary calls 28 ms vs 5 ms; 64-bit hash BigInt ≈ 146 ms vs Wasm 9 ms.
Pitfalls
- Caching HTML cache-first with no update path; never deleting old caches; a broken
sw.jscached forever (serve it withCache-Control: no-cache). - Expecting the first page load to be controlled without
clients.claim(). - Posting huge objects to workers instead of transferring buffers.
- Using Wasm for UI logic or making fine-grained calls across the boundary.
- Shipping multi-megabyte Wasm without streaming compilation, compression and caching.
Glossary
- PWA: a web app with a manifest and service worker that can install and work offline.
- App shell: the minimal HTML, CSS and JS needed to render the UI, cached for instant loads.
- Transferable: an object whose ownership moves to another thread without copying.
- Linear memory: a Wasm module's single resizable byte array.
- WASI: the WebAssembly System Interface for running Wasm outside browsers.
- Cross-origin isolation: the COOP + COEP state that unlocks
SharedArrayBufferand precise timers.