WebAssembly.compile()

这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。

WebAssembly.compile() 方法编译WebAssembly二进制代码到一个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

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.Module.exports 属性来调用模块上返回的可用信息。

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]);
};

Specifications

Specification Status Comment
WebAssembly JavaScript Interface
compile()
Working Draft Initial draft definition.

Browser compatibility

Update compatibility data on GitHub
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
compile Chrome Full support 57 Edge Full support 16 Firefox Full support 52
Notes
Full support 52
Notes
Notes Disabled in the Firefox 52 Extended Support Release (ESR).
IE No support No Opera Full support 44 Safari Full support 11 WebView Android Full support 57 Chrome Android Full support 57 Firefox Android Full support 52
Notes
Full support 52
Notes
Notes Disabled in the Firefox 52 Extended Support Release (ESR).
Opera Android Full support 43 Safari iOS Full support 11 Samsung Internet Android Full support 7.0 nodejs Full support 8.0.0

Legend

Full support  
Full support
No support  
No support
See implementation notes.
See implementation notes.

See also