Loading and running WebAssembly code


要在JavaScript中使用WebAssembly,您首先需要在编译/实例化之前将模块拉入内存。模块最初将被捕获为类型化的数组, 例如. 通过 XMLHttpRequestFetch,但将来可能会有更多的选择。 本文提供了可用于获取WebAssembly字节码的不同机制的参考,以及如何编译/实例化然后运行它。

What's the issue here?

WebAssembly is not yet integrated with <script type='module'> or ES6 import statements, thus there is not currently a built-in way to have the browser fetch modules for you. The only current option is to create an ArrayBuffer containing your WebAssembly module binary, and compile it using for example WebAssembly.instantiate(). This is analogous to new Function(string), except that we are substituting a string of characters (JavaScript source code) with an array buffer of bytes (WebAssembly source code).

So how do we get those bytes into an array buffer and compiled? The following sections explain.

Using Fetch

Fetch is a convenient, modern API for fetching network resources.

Let's say we have a WebAssembly module on the network called simple.wasm:

  • We can fetch it easily using the fetch() global function, which returns a promise that contains the result in a Response object when it resolves.
  • We can convert the response into a typed array using the arrayBuffer() function. The returns a promise that resolves to the typed array.
  • Finally, we can compile and instantiate the typed array in one action using the WebAssembly.instantiate() function.

The necessary code block would look like this:

fetch('module.wasm').then(response =>
).then(bytes =>
  WebAssembly.instantiate(bytes, importObject)
).then(results => {
  // Do something with the compiled results!

Aside on instantiate() overloads

The WebAssembly.instantiate() function has to overload forms — the one shown above takes the byte code to compile as an argument and returns a promise that resolves to an object containing both the compiled module object, and an instantiated instance of it. The object looks like this:

  module : Module // The newly compiled WebAssembly.Module object,
  instance : Instance // A new WebAssembly.Instance of the module object

Note: Usually we only care about the instance, but it’s useful to have the module in case we want to cache it, share it with another worker or window via postMessage(), or simply create more instances.

Note: The second overload form takes a WebAssembly.Module object as an argument, and returns a promise directly containing the instance object as the result. See Second overload example.

Fetch and instantiate utility function

The above code pattern works, but it is somewhat long winded and laborious to write out every time, especially if you want to load multiple modules. To make it easier, we have created a utility function called fetchAndInstantiate(), which deals with this in the background by returning a single promise. You can find this function in wasm-utils.js, and it looks like this:

function fetchAndInstantiate(url, importObject) {
  return fetch(url).then(response =>
  ).then(bytes =>
    WebAssembly.instantiate(bytes, importObject)
  ).then(results =>

After including this in your HTML, you can then fetch, instantiate, and access an instance of a WebAssembly module with one simple line:

fetchAndInstantiate('module.wasm', importObject).then(function(instance) {

Note: You can see many examples of this in action around our documentation (for example, see index.html) — this is the standard pattern we recommend for loading modules.

Running your WebAssembly code

Once you've got your WebAssembly instance available in your JavaScript, you can then start using features of it that have been exported via the WebAssembly.Instance.exports property. Your code might look something like this:

fetchAndInstantiate('myModule.wasm', importObject).then(function(instance) {
  // Call an exported function:

  // or access the buffer contents of an exported memory:
  var i32 = new Uint32Array(instance.exports.memory.buffer);

  // or access the elements of an exported table:
  var table = instance.exports.table;

Note: For more information on how exporting from a WebAssembly module works, have a read of Using the WebAssembly JavaScript API, and Understanding WebAssembly text format.

Using XMLHttpRequest

XMLHttpRequest is somewhat older than Fetch, but can still be happily used to get a typed array. Again, assuming our module is called simple.wasm:

  1. Create a new XMLHttpRequest() instance, and use its open() method to open a request, setting the request method to GET, and declaring the path to the file we want to fetch.
  2. The key part of this is to set the response type to 'arraybuffer' using the responseType property.
  3. Next, send the request using XMLHttpRequest.send().
  4. We then use the onload event handler to invoke a function when the response has finished downloading — in this function we get the array buffer from the response property, and then feed that into our WebAssembly.instantiate() method as we did with Fetch.

The final code looks like this:

request = new XMLHttpRequest();
request.open('GET', 'simple.wasm');
request.responseType = 'arraybuffer';

request.onload = function() {
  var bytes = request.response;
  WebAssembly.instantiate(bytes, importObject).then(results => {

Note: You can an example of this in action in xhr-wasm.html.


 此页面的贡献者: xgqfrms-GitHub
 最后编辑者: xgqfrms-GitHub,