WebAssembly.Module
BaselineWidely 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.Module
对象包含已经由浏览器编译的无状态 WebAssembly 代码,可以高效地与 Worker 共享和多次实例化。
构造函数
WebAssembly.Module()
创建一个新的
Module
对象。
静态属性
WebAssembly.Module.customSections()
给定一个
Module
和字符串,返回模块中具有给定字符串名称的所有自定义的部分的内容副本。WebAssembly.Module.exports()
给定一个
Module
,返回一个数组,其中包含所有声明的导出的描述。WebAssembly.Module.imports()
给定一个
Module
,返回一个数组,其中包含所有声明的导入的描述。
示例
将编译后的模块发送到 worker
以下示例将使用WebAssembly.compileStreaming()
方法编译simple.wasm
加载后的字节码,并将返回的Module
实例通过postMessage()
发送到一个worker。
参见index-compile.html
的源代码,或查看在线演示。
js
const worker = new Worker("wasm_worker.js");WebAssembly.compileStreaming(fetch("simple.wasm")).then((mod) => worker.postMessage(mod),);
Worker 函数wasm_worker.js
定义了模块需要使用的导入对象。然后,该函数会创建一个事件处理器,以接受主线程发送的模块。在接收到模块后,我们使用WebAssembly.instantiate()
方法创建一个它的实例,然后调用其导出的函数。
js
const importObject = { imports: { imported_func(arg) { console.log(arg); }, },};onmessage = (e) => { console.log("module received from main thread"); const mod = e.data; WebAssembly.instantiate(mod, importObject).then((instance) => { instance.exports.exported_func(); });};
规范
Specification |
---|
WebAssembly JavaScript Interface # modules |