Loading & Running WASM in JavaScript
Learn how to load your compiled WASM module in a web browser using JavaScript and invoke its exported functions.
Loading & Running WASM in JavaScript is a free WebAssembly (WASM) for High Performance Apps lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the WebAssembly (WASM) for High Performance Apps learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Getting WASM into the Browser
Welcome! You've learned how to compile C/C++ code into a .wasm file. Now, it's time to bring that powerful WebAssembly module to life in your web browser.
This lesson will guide you through loading your .wasm module using JavaScript and invoking its functions.
Browser's WASM Gateway
Modern web browsers provide a global WebAssembly object. This object is your primary interface for interacting with WebAssembly modules.
- It allows you to compile, instantiate, and manage WASM code.
- We'll use its methods to fetch and load our
.wasmfile into the browser's runtime.
Streamlined WASM Loading
The most efficient way to load a WASM module from a network request is using WebAssembly.instantiateStreaming().
- It directly streams the raw bytes from the network response.
- It compiles and instantiates the module in one go, saving time and resources.
- This method expects a
Responseobject, typically obtained from thefetch()API.
Our Simple C Function
Let's assume we have a very basic C function that adds two numbers, like this one. This function will be compiled into add.wasm (as covered in the previous lesson) and then exported from the WASM module.
This export makes it callable directly from JavaScript.
/* add.c */
int add(int a, int b) {
return a + b;
}Fetching the .wasm File
Before we can instantiate our WASM module, we need to fetch the .wasm file itself. The standard fetch() API is perfect for this task.
It returns a Promise that resolves to a Response object, which we'll then pass to instantiateStreaming().
async function fetchWasmModule() {
const response = await fetch('add.wasm');
// Check if the request was successful
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response;
}Instantiating the WASM Module
The WebAssembly.instantiateStreaming() function takes the Response and returns a Promise. This Promise resolves to an object containing two important properties:
module: The compiled WebAssembly module itself.instance: An object representing the running instance of the module, which holds its exports.
async function loadAndInstantiate() {
const response = await fetch('add.wasm');
const wasmObject = await WebAssembly.instantiateStreaming(response);
console.log(wasmObject); // Shows { module: WebAssembly.Module, instance: WebAssembly.Instance }
return wasmObject.instance;
}Accessing Exported Functions
Once you have the instance object, you can access any functions or global variables that were exported from your WASM module. These are available through its exports property.
For our C add function, when compiled to WASM and exported, it will be accessible in JavaScript as instance.exports.add.
Full Example: Load & Call WASM
Here's a complete JavaScript code snippet. It fetches add.wasm, instantiates it, and then calls the exported add function with two numbers, logging the result.
This code would run inside a <script> tag in an HTML file.
async function runWasmAdder() {
try {
const response = await fetch('add.wasm');
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const { instance } = await WebAssembly.instantiateStreaming(response);
// Call the exported 'add' function
const num1 = 15;
const num2 = 25;
const sum = instance.exports.add(num1, num2);
console.log(`${num1} + ${num2} = ${sum}`);
// Expected output: "15 + 25 = 40"
} catch (error) {
console.error("Error loading or running WASM:", error);
}
}
runWasmAdder();Inside the Instance Object
The instance object is your primary interface to the running WebAssembly module. It contains more than just exported functions:
instance.exports: An object holding all functions, globals, and memory exported by the WASM module.instance.module: A reference to the compiledWebAssembly.Moduleobject.instance.memory: If the WASM module uses memory, this provides access to its linear memory (anArrayBuffer).
Quick Check: WASM Loading
You've seen how to efficiently load and instantiate a WASM module. What is the key JavaScript function used for this purpose when streaming from a network request?
Recap: WASM in the Browser
Fantastic work! You've successfully learned how to bring your compiled WebAssembly modules to life in the browser. Here's what we covered:
- Using the global
WebAssemblyobject. - Efficiently loading with
WebAssembly.instantiateStreaming(). - Accessing exported functions via the
instance.exportsobject. - Calling WASM functions directly from JavaScript.
Now you can execute high-performance code right in your web applications!
Frequently asked questions
Is the “Loading & Running WASM in JavaScript” lesson free?
Yes — the full text of “Loading & Running WASM in JavaScript” is free to read here on the web, and the WebAssembly (WASM) for High Performance Apps course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the WebAssembly (WASM) for High Performance Apps course, upgrade to CoddyKit PRO.
What will I learn in “Loading & Running WASM in JavaScript”?
Learn how to load your compiled WASM module in a web browser using JavaScript and invoke its exported functions. You practise WebAssembly (WASM) for High Performance Apps with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start WebAssembly (WASM) for High Performance Apps?
No prior experience is required. WebAssembly (WASM) for High Performance Apps on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Loading & Running WASM in JavaScript” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this WebAssembly (WASM) for High Performance Apps lesson?
Yes. Every WebAssembly (WASM) for High Performance Apps lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Compiling C/C++ to WASM with Emscripten
- Loading & Running WASM in JavaScript
- Basic Data Exchange: Primitives
- Calling JavaScript Functions from C/C++