WebAssembly.Module 对象包含已经由浏览器编译的无状态 WebAssembly 代码,可以高效地与 Worker 共享和多次实例化。
首先写webassemblyModule.wat
当然这里的wat要转换成wasm才能被javascript调用
(module
(func $i (import "my_namespace" "imported_func")(param i32))
(func (export "exported_func")
i32.const 42
call $i
)
)
然后 是js文件
webassemblyModule.js
//建立importObj对象,由上面的wat文件调用,并导入这个imported_func函数
const importObj={
my_namespace:{
imported_func:arg=>{
console.log(arg);
}
}
};
//这里是worker发送过来的数据,当然这个数据提一个由wasm构成的模块,里面包括了exported_func函数
self.onmessage=(e)=>{
console.log('从主线程接收的模块');
const mod=e.data;
console.log(mod);
//创建webAssemlby.instatiate实例,接收模块,并导入importObj对象进模块中
WebAssembly.instantiate(mod,importObj)
.then(instance=>{
instance.exports.exported_func();//实例调用导出的函数
});
const exports=WebAssembly.Module.exports(mod);//直接导出模块
console.log(exports[0]);//查看函数
}
//这里是html文件,worker调用webassmblyModule.js文件,在线程中执行js文件
//index.html
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
<title>测试webAssembly的module导出模式中所有函数用worker传递函数并调用</title>
</head>
<body>
<script type="text/javascript">
let worker=new Worker("webassemblyModule.js");//主线程执行js文件
console.log(worker);
//这里有两种方法来实现发送wasm中模块,第一种方法用webAssembly.compileStreaming()流文件方式
/*
WebAssembly.compileStreaming(fetch('./webassemblyModule.wasm'))
.then((mod)=>{
console.log(mod);
worker.postMessage(mod);//发送模块
})
*/
//第二种方法,先读取wasm中的内容,再获取内存当中的二进制文件,然后用webassembly.module()方法获取二进制文件的模块
fetch("./webassemblyModule.wasm")
.then((response)=>response.arrayBuffer())
.then((bytes)=>{
let module=new WebAssembly.Module(bytes);
console.log(module);
worker.postMessage(module);//发送模块
})
</script>
</body>
</html>