WebAssembly.compileStreaming()
Baseline 广泛可用 *
WebAssembly.compileStreaming()
静态方法直接从流式底层源编译 WebAssembly.Module
。如果需要在实例化之前编译模块(否则应使用 WebAssembly.instantiateStreaming()
函数),此函数非常有用。
注意: 具有严格 Content Security Policy (CSP) 的网页可能会阻止 WebAssembly 编译和执行模块。有关允许 WebAssembly 编译和执行的更多信息,请参阅 script-src CSP。
语法
WebAssembly.compileStreaming(source)
WebAssembly.compileStreaming(source, compileOptions)
参数
source
-
一个
Response
对象或一个将解析为该对象的 Promise,代表您想要流式传输和编译的 Wasm 模块的底层源。 compileOptions
可选-
一个包含编译选项的对象。属性可以包括:
builtins
可选-
一个字符串数组,用于启用在已编译的 Wasm 模块中使用 JavaScript 内置函数。这些字符串定义了您要启用的内置函数。目前唯一可用的值是
"js-string"
,它启用 JavaScript 字符串内置函数。 importedStringConstants
可选-
一个字符串,指定 导入的全局字符串常量 的命名空间。如果您希望在 Wasm 模块中使用导入的全局字符串常量,则需要指定此属性。
返回值
一个 Promise
,它将解析为代表已编译模块的 WebAssembly.Module
对象。
异常
- 如果
source
不是Response
或解析为Response
的Promise
,则该 Promise 会因TypeError
而拒绝。 - 如果编译失败,则 Promise 会因
WebAssembly.CompileError
而拒绝。 - 如果
source
是一个拒绝的Promise
,则 Promise 会因该错误而拒绝。 - 如果
source
的Result
有错误(例如,MIME 类型错误),则 Promise 会因错误而拒绝。
示例
编译流式传输
以下示例(请参阅 GitHub 上的 compile-streaming.html 演示,并 实时查看)直接从底层源流式传输 Wasm 模块,然后将其编译为 WebAssembly.Module
对象。因为 compileStreaming()
函数接受一个 Response
对象的 Promise,所以您可以直接将其传递给调用 fetch()
获得的 Promise,而无需等待 Promise fulfilled。
const importObject = {
my_namespace: { imported_func: (arg) => console.log(arg) },
};
WebAssembly.compileStreaming(fetch("simple.wasm"))
.then((module) => WebAssembly.instantiate(module, importObject))
.then((instance) => instance.exports.exported_func());
然后使用 WebAssembly.instantiate()
实例化结果模块实例,并调用导出的函数。
启用 JavaScript 内置函数和全局字符串导入
此示例在使用 compileStreaming()
编译 Wasm 模块时启用 JavaScript 字符串内置函数和导入的全局字符串常量,然后在用 instantiate()
实例化然后运行导出的 main()
函数(该函数将 "hello world!"
记录到控制台)之前。 实时查看其运行效果。
const importObject = {
// Regular import
m: {
log: console.log,
},
};
const compileOptions = {
builtins: ["js-string"], // Enable JavaScript string builtins
importedStringConstants: "string_constants", // Enable imported global string constants
};
WebAssembly.compileStreaming(fetch("log-concat.wasm"), compileOptions)
.then((module) => WebAssembly.instantiate(module, importObject))
.then((instance) => instance.exports.main());
规范
规范 |
---|
WebAssembly Web API # dom-webassembly-compilestreaming |
浏览器兼容性
加载中…