WebAssembly.instantiateStreaming() - JavaScript 编辑
The WebAssembly.instantiateStreaming()
function compiles and instantiates a WebAssembly module directly from a streamed underlying source. This is the most efficient, optimized way to load wasm code.
Syntax
Promise<ResultObject> WebAssembly.instantiateStreaming(source, importObject);
Parameters
- source
- A
Response
object or a promise that will fulfill with one, representing the underlying source of a .wasm module you want to stream, compile, and instantiate. - importObject Optional
- An object containing the values to be imported into the newly-created
Instance
, such as functions orWebAssembly.Memory
objects. There must be one matching property for each declared import of the compiled module or else aWebAssembly.LinkError
is thrown.
Return value
A Promise
that resolves to a ResultObject
which contains two fields:
module
: AWebAssembly.Module
object representing the compiled WebAssembly module. ThisModule
can be instantiated again or shared via postMessage().instance
: AWebAssembly.Instance
object that contains all the Exported WebAssembly functions.
Exceptions
- If either of the parameters are not of the correct type or structure, a
TypeError
is thrown. - If the operation fails, the promise rejects with a
WebAssembly.CompileError
,WebAssembly.LinkError
, orWebAssembly.RuntimeError
, depending on the cause of the failure.
Examples
Instantiating streaming
The following example (see our instantiate-streaming.html demo on GitHub, and view it live also) directly streams a .wasm module from an underlying source then compiles and instantiates it, the promise fulfilling with a ResultObject
. Because the instantiateStreaming()
function accepts a promise for a Response
object, you can directly pass it a WindowOrWorkerGlobalScope.fetch()
call, and it will pass the response into the function when it fulfills.
var importObject = { imports: { imported_func: arg => console.log(arg) } };
WebAssembly.instantiateStreaming(fetch('simple.wasm'), importObject)
.then(obj => obj.instance.exports.exported_func());
The ResultObject
's instance member is then accessed, and the contained exported function invoked.
Note: For this to work, .wasm
files should be returned with an application/wasm
MIME type by the server.
Specifications
Specification |
---|
WebAssembly features for web embedding The definition of 'instantiateStreaming()' in that specification. |
Browser compatibility
BCD tables only load in the browser
See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论