WebAssembly.compile()

Baseline Widely available *

This feature is well established and works across many devices and browser versions. It’s been available across browsers since October 2017.

* Some parts of this feature may have varying levels of support.

WebAssembly.compile() 方法编译 WebAssembly 二进制代码到一个WebAssembly.Module 对象。如果在实例化之前有必要去编译一个模块,那么这个方法是有用的(否则,将会使用WebAssembly.instantiate() 方法)

语法

Promise<WebAssembly.Module> WebAssembly.compile(bufferSource);

参数

bufferSource

一个包含你想编译的 wasm 模块二进制代码的 typed array(类型数组) or ArrayBuffer(数组缓冲区)

返回值

一个会兑现为 WebAssembly.ModulePromise 对象。

异常

示例

下面的例子 (查看 GitHub 上的 index-compile.html 例子,并且也能 查看运行效果) 使用 compile() 方法编译加载进来的 simple.wasm 二进制代码并且使用 postMessage() 发送给一个 worker

js
var worker = new Worker("wasm_worker.js");

fetch("simple.wasm")
  .then((response) => response.arrayBuffer())
  .then((bytes) => WebAssembly.compile(bytes))
  .then((mod) => worker.postMessage(mod));

在线程中(查看 wasm_worker.js)我们定义了一个导入对象共模块使用,然后设置了一个事件处理函数来接收主线程发送过来的模块。当模块被接收之后,我们使用WebAssembly.Instantiate() 方法创建了一个实例,调用从它里面导出的一个方法,接下来展示了我们可以用 WebAssembly.Module.exports 属性来调用模块上返回的可用信息。

js
var importObject = {
  imports: {
    imported_func: function (arg) {
      console.log(arg);
    },
  },
};

onmessage = function (e) {
  console.log("module received from main thread");
  var mod = e.data;

  WebAssembly.instantiate(mod, importObject).then(function (instance) {
    instance.exports.exported_func();
  });

  var exports = WebAssembly.Module.exports(mod);
  console.log(exports[0]);
};

规范

Specification
WebAssembly JavaScript Interface
# dom-webassembly-compile

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
compile() static method
compileOptions parameter

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support

参见