0Pricing
WebAssembly (WASM) for High Performance Apps · Урок

Загрузка и запуск WASM в JavaScript

Научитесь загружать скомпилированный модуль WASM в веб-браузере с помощью JavaScript и вызывать экспортированные функции

«Загрузка и запуск WASM в JavaScript» — бесплатный урок WebAssembly (WASM) for High Performance Apps на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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!

Часто задаваемые вопросы

Урок «Загрузка и запуск WASM в JavaScript» бесплатный?

Да — полный текст урока «Загрузка и запуск WASM в JavaScript» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс WebAssembly (WASM) for High Performance Apps, подпишись на CoddyKit PRO. Курс WebAssembly (WASM) for High Performance Apps содержит 4 уроков всего.

Чему я научусь в уроке «Загрузка и запуск WASM в JavaScript»?

Научитесь загружать скомпилированный модуль WASM в веб-браузере с помощью JavaScript и вызывать экспортированные функции Ты практикуешь WebAssembly (WASM) for High Performance Apps с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать WebAssembly (WASM) for High Performance Apps?

Предыдущий опыт не требуется. WebAssembly (WASM) for High Performance Apps на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Загрузка и запуск WASM в JavaScript»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке WebAssembly (WASM) for High Performance Apps?

Да. Каждый урок WebAssembly (WASM) for High Performance Apps включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Компиляция C/C++ в WASM с Emscripten
  2. Загрузка и запуск WASM в JavaScript
  3. Базовый обмен данными: примитивы
  4. Вызов функций JavaScript из C/C++
← Назад к WebAssembly (WASM) for High Performance Apps