Back to Blog

Web Platform Standards & Modern Web Guidance

Modern Web Guidance
WebAssembly

Run fast C and C++ code in the browser without freezing the page. See how to compile it with Emscripten, pass data through WebAssembly's linear memory and keep heavy work off the main thread, then try each step live on this page.

Baseline Status
Widely Available

In every core browser since October 2017, and Widely available since April 2020.

MWG Guide ID
cpp-on-the-web

Compiles C and C++ using Emscripten with modular ES exports.

Main-Thread Rule
A few ms

Any Wasm call longer than a few milliseconds must not run synchronously on the main thread.

INP Target (p75)
≤ 200 ms

Real-user responsiveness threshold across at least 75% of page visits.

01 / Foundations & Core Concepts

WebAssembly complements JavaScript as a Baseline Widely Available standard

Rather than replacing JavaScript, WebAssembly provides a portable, compact binary execution target inside the browser sandbox for deterministic, compute-heavy workloads.

What WebAssembly actually is

WebAssembly (often shortened to Wasm) is a low-level, binary instruction format designed as a portable compilation target for languages such as C, C++ and Rust. Think of standard JavaScript as a skilled front-of-house manager: it handles user clicks, updates the Document Object Model (DOM), orchestrates network requests and coordinates page layout. WebAssembly acts like a specialist fabrication workshop in the back room: you hand it raw numerical data, it runs tight mathematical loops at near-native machine speed and it passes the finished numbers straight back.

Because a .wasm file ships as pre-parsed compact binary bytecode rather than plain text source code, browsers can decode, validate and compile it far faster than an equivalent volume of hand-written JavaScript. Every instruction operates inside strict memory bounds enforced by the browser engine.

Why Modern Web Guidance includes WebAssembly

Large language models (LLMs) trained on older repositories frequently make poor architectural choices when asked to handle heavy client-side tasks: they either re-implement complex image, audio or cryptographic algorithms slowly in unoptimised JavaScript, or they pull in bloated legacy dependencies. Modern Web Guidance (stewarded by the Google Chrome, Microsoft Edge, Mozilla Firefox and MDN teams) closes that knowledge gap by supplying coding agents with vetted patterns at generation time.

Under the wasm category, Modern Web Guidance publishes the cpp-on-the-web guide: concrete guidance for developers and AI agents on compiling C and C++ with Emscripten: recommended compiler flags, efficient calls across the JavaScript boundary, keeping heavy work off the main thread, testing for memory and stack limits, and porting existing libraries.

W3C WebDX Baseline Governance
Browser Engine Core Browsers Core Wasm
Chromium (Blink / V8) Chrome & Edge Supported
Gecko (SpiderMonkey) Firefox (Desktop & Android) Supported
WebKit (JavaScriptCore) Safari (macOS & iOS) Supported

Baseline tracks web features through three stages under the W3C WebDX Community Group: Limited Availability (missing in at least one core engine), Newly Available (supported in every core browser) and Widely Available (30 months after that). Core WebAssembly has been Baseline Widely Available since April 2020, so it needs no polyfills or asm.js fallbacks.

Modern Web Guidance Rule: Right Tool for the Task

Do not rewrite ordinary DOM interactions, form validation or simple state logic in WebAssembly. Crossing the boundary between JavaScript and Wasm carries a small call overhead; reserve Wasm for sustained numerical computation such as media codecs, physics simulations, CAD kernels, compression or cryptography.

JavaScript Strengths

DOM, Events & Orchestration

Direct access to HTML elements, CSS custom properties, Web APIs, network fetching and asynchronous event loops with zero serialisation overhead.

WebAssembly Strengths

Predictable Throughput

Statically typed arithmetic, predictable memory layout, no garbage-collection pauses for C and C++ code in linear memory, and portable execution of battle-tested C and C++ libraries.

Progressive Enhancement

Baseline-Aware Extensions

Core Wasm is Widely Available, but newer extensions are not: WasmGC and JavaScript Promise Integration are Newly Available, and Relaxed SIMD and Memory64 are still Limited. Feature-detect them or check them against your project's Baseline target.

02 / The C/C++ to WebAssembly Pipeline

Compiling with Emscripten (emcc) and inspecting linear memory

Modern Web Guidance (cpp-on-the-web) standardises on Emscripten to transform C and C++ into compact .wasm modules paired with ES module JavaScript glue code.

How Emscripten builds for the browser

Emscripten is a complete compiler toolchain built on top of Clang and LLVM. Instead of targeting an x86 or ARM processor, emcc lowers your C or C++ source code into LLVM Intermediate Representation (IR), optimises it and emits two coordinated artefacts: a binary .wasm module containing the compiled machine instructions and a thin JavaScript glue file (an ES module when you use -sEXPORT_ES6) that sets up memory, resolves browser imports and exposes your exported C functions as an asynchronous factory.

Beginners often compile with default flags, which creates global variables on window, bundles unnecessary Node.js filesystem shims and allows the linker to strip out C functions that main() never calls. Modern Web Guidance recommends a short set of modern flags to keep output modular, small and strict, and to write them without redundant defaults, =1 suffixes or JSON-style lists.

emcc Flag Purpose & Guidance
-O3 / -Os / -Oz with -flto -O3 when runtime speed matters most, -Os or -Oz when payload size matters most. Add -flto to both compile and link steps for link-time optimisation.
-sSTRICT Opts into strict modern Emscripten behaviour and disables deprecated legacy features.
-sEXPORT_ES6 Emits a standard ES module and implies -sMODULARIZE, so the generated code doesn't pollute the global scope.
-sEXPORTED_FUNCTIONS=_invert,_malloc,_free Keeps the C functions JavaScript calls (names start with an underscore). Write lists comma-separated, without brackets or quotes.
-sEXPORTED_RUNTIME_METHODS=HEAPU8 Exposes runtime helpers such as the HEAPU8 typed-array view (or ccall and cwrap).
-sALLOW_MEMORY_GROWTH Lets linear memory grow in 64 KiB pages when allocations exceed the initial heap.
-sENVIRONMENT=web,worker Strips Node.js and shell support code. Use web or worker alone if the module only runs in one of them.
-Werror -Wall Treats compiler warnings as errors so C and C++ bugs and invalid settings surface early.
Interactive Lab 01 Emscripten Compiler & Linear Memory Inspector
Compilation Flags
Source Preview
 
Generated CLI Command
Toolchain Stages
1. Clang ASTParse C/C++
2. LLVM IROptimise
3. wasm-ldLink Symbols
4. Binaryen + emccOptimise .wasm, emit JS
Build Output (illustrative sizes)

Linear Memory Inspector (64-Byte Window of WebAssembly.Memory)

Observe how JavaScript allocates a pointer with _malloc, writes bytes into HEAPU8, triggers C execution and releases memory with _free.

Heap idle (0 bytes allocated)
Unallocated page bytes Allocated buffer (0x0010 to 0x001F) Mutated in-place by Wasm
Pointer: null
03 / Performance & Core Web Vitals

Protecting the main thread to keep Interaction to Next Paint under 200 ms

Fast execution does not automatically guarantee a responsive interface. Modern Web Guidance says heavy WebAssembly work must not run synchronously on the main thread, and recommends running it in a Web Worker.

Why Core Web Vitals demand non-blocking execution

Google assesses Core Web Vitals at the 75th percentile of real-user field visits: Largest Contentful Paint (LCP) must land at or below 2.5 seconds, Cumulative Layout Shift (CLS) at or below 0.1 and Interaction to Next Paint (INP) at or below 200 milliseconds. A fast score on a developer laptop cannot mask sluggish responsiveness on a mid-range mobile device.

By default, JavaScript and synchronous WebAssembly calls run on the browser's single main thread alongside layout, painting and input handling. Any task longer than 50 ms counts as a long task and delays taps, clicks and keystrokes. The cpp-on-the-web guide sets a stricter bar for WebAssembly: any call that takes more than a few milliseconds, such as image rendering, physics or heavy parsing, must not run synchronously on the main thread.

Web Workers + Transferable ArrayBuffers

When your C or C++ module processes megabytes of audio, image pixels or simulation geometry, run it inside a dedicated module Web Worker (new Worker(new URL('./worker.js', import.meta.url), { type: 'module' })). Instead of copying large typed arrays across threads, pass the underlying ArrayBuffer as a Transferable object in worker.postMessage(buffer, [buffer]): ownership transfers instantaneously in constant time, leaving the main thread free to paint frames at 60 Hz.

The guide gives two other options. Multithreading with -pthread spreads work across background threads, but needs SharedArrayBuffer, so the page must be cross-origin isolated (Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp). Or restructure continuous C/C++ loops to run one frame at a time with emscripten_set_main_loop, using JavaScript Promise Integration (-sJSPI) or Asyncify when synchronous code must wait for asynchronous JavaScript.

Core Web Vitals Guardrails (75th Percentile)
Metric Good Target Wasm & Worker Impact
INP (Responsiveness) ≤ 200 ms Worker offloading keeps long Wasm calls from stalling clicks and filters on the main thread.
LCP (Loading) ≤ 2.5 s Smaller binaries (-Os/-Oz) and streaming compilation keep Wasm loading from delaying the main content.
CLS (Visual Stability) ≤ 0.1 Reserve explicit canvas or output dimensions before Wasm renders frames.

Network Delivery: Brotli & Zstandard

HTTP compression shrinks .wasm payloads over the wire. Brotli is Baseline Widely Available, and Zstandard became Baseline Newly Available in February 2026.

Interactive Lab 02 Main Thread vs Web Worker + Wasm INP Simulator
Execution Strategy
Measured Telemetry & Core Web Vitals Assessment
Main Thread Block
0 ms
Simulated INP
12 ms
CWV Status
Good (≤ 200 ms)

Choose an execution strategy above and click “Test UI Tap” immediately afterwards to compare frame responsiveness and INP breakdown. Timings are illustrative.

60 Hz Frame Budget & Thread Timeline (ms) MAIN THREAD (UI, INPUT & PAINT) WEB WORKER THREAD (WASM KERNEL) 0 ms 50 ms (Long Task) 200 ms (INP Limit) 320 ms
04 / Architecture & Mechanics

Inside the sandbox: linear memory, typed arrays and streaming compilation

Understanding how WebAssembly isolates execution stacks, bridges data across JavaScript typed arrays and compiles bytes progressively off the network.

Network Layer

Streaming Compilation & Instantiation

Implementation Requirement

Memory Page Unit

64 KiB Granularity

WebAssembly memory allocates and grows in fixed 65,536-byte (64 KiB) pages. A request to memory.grow(n) appends n pages and detaches stale JavaScript TypedArray views, requiring fresh views afterwards.

Number-Only Boundary

Marshalling Strings & Structs

Compiled C and C++ functions take numbers (i32, i64, f32, f64), not JavaScript strings or objects. To pass a string, JavaScript encodes UTF-8 bytes via TextEncoder into linear memory and passes the starting byte offset and byte length.

Hardened Isolation

Zero Direct Hardware Access

Wasm modules have no intrinsic filesystem, network or DOM access. Every external capability must be explicitly granted by JavaScript inside the importObject, preserving Same-Origin Policy and CSP boundaries.

05 / Practical Code Examples

Annotated production patterns from compilation to Worker offload

Inspect each stage of a standards-compliant WebAssembly integration. Select a file and click any step to highlight the exact lines responsible.

06 / Learner Knowledge Check

Test your grasp of Modern Web Guidance & WebAssembly

Six scenario-based questions covering Baseline compatibility, Emscripten flags, linear memory safety and Core Web Vitals protection. Your answers are saved in this browser.

Score: 0 / 6 0 of 6 answered

Sources & Attribution