0Pricing
WebAssembly (WASM) for High Performance Apps · 课时

在 JavaScript 中加载并运行 WASM

学习如何在 Web 浏览器中使用 JavaScript 加载编译后的 WASM 模块,并调用其导出函数

在 JavaScript 中加载并运行 WASM 是 CoddyKit 上的免费 WebAssembly (WASM) for High Performance Apps 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 WebAssembly (WASM) for High Performance Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 WebAssembly (WASM) for High Performance Apps 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

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 .wasm file 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 Response object, typically obtained from the fetch() 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 compiled WebAssembly.Module object.
  • instance.memory: If the WASM module uses memory, this provides access to its linear memory (an ArrayBuffer).

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 WebAssembly object.
  • Efficiently loading with WebAssembly.instantiateStreaming().
  • Accessing exported functions via the instance.exports object.
  • Calling WASM functions directly from JavaScript.

Now you can execute high-performance code right in your web applications!

常见问题解答

「在 JavaScript 中加载并运行 WASM」课时是免费的吗?

是的 — 「在 JavaScript 中加载并运行 WASM」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 WebAssembly (WASM) for High Performance Apps 课程的其余内容,请升级到 CoddyKit PRO。 WebAssembly (WASM) for High Performance Apps 课程共包含 4 节课。

「在 JavaScript 中加载并运行 WASM」这节课中我会学到什么?

学习如何在 Web 浏览器中使用 JavaScript 加载编译后的 WASM 模块,并调用其导出函数 你通过在浏览器中直接运行的动手代码来练习 WebAssembly (WASM) for High Performance Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 WebAssembly (WASM) for High Performance Apps 需要有经验吗?

无需任何先前经验。CoddyKit 上的 WebAssembly (WASM) for High Performance Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「在 JavaScript 中加载并运行 WASM」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 WebAssembly (WASM) for High Performance Apps 课中编写并运行代码吗?

能。每节 WebAssembly (WASM) for High Performance Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 Emscripten 将 C/C++ 编译为 WASM
  2. 在 JavaScript 中加载并运行 WASM
  3. 基本数据交换:原始类型
  4. 从 C/C++ 调用 JavaScript 函数
← 返回 WebAssembly (WASM) for High Performance Apps