WebAssembly.compileStreaming()
Baseline Widely 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.compileStreaming()
静态方法直接将流式传输的底层源码编译为一个 WebAssembly.Module
对象。如果在实例化模块之前必须要对其进行编译,那么这个函数就是有用的(否则,应该使用 WebAssembly.instantiateStreaming()
函数)。
备注: 有严格内容安全策略(CSP)的网页可能会阻止 WebAssembly 编译和执行模块。有关允许编译和执行 WebAssembly 的更多信息,参见 script-src CSP。
语法
WebAssembly.compileStreaming(source)
WebAssembly.compileStreaming(source, compileOptions)
参数
source
-
一个
Response
对象或者一个能兑现它的 promise,该对象代表的是你想流式编译的底层源码。 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 兑现。
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 = {
// 常规导入
m: {
log: console.log,
},
};
const compileOptions = {
builtins: ["js-string"], // 启用 JavaScript 字符串内置功能
importedStringConstants: "string_constants", // 启用导入的全局字符串常量
};
WebAssembly.compileStreaming(fetch("log-concat.wasm"), compileOptions)
.then((module) => WebAssembly.instantiate(module, importObject))
.then((instance) => instance.exports.main());
规范
Specification |
---|
WebAssembly Web API # dom-webassembly-compilestreaming |