WebAssembly.compileStreaming()
WebAssembly.compileStreaming() 靜態方法直接從流式底層原始碼編譯 WebAssembly.Module。如果需要在模組例項化之前編譯模組,此函式很有用(否則,應該使用 WebAssembly.instantiateStreaming() 函式)。
注意: 具有嚴格 內容安全策略 (CSP) 的網頁可能會阻止 WebAssembly 編譯和執行模組。有關允許 WebAssembly 編譯和執行的更多資訊,請參閱 script-src CSP。
語法
js
WebAssembly.compileStreaming(source)
引數
返回值
一個承諾,該承諾解析為 WebAssembly.Module 物件,代表已編譯的模組。
異常
- 如果
source不是Response或解析為Response的承諾,則承諾將拒絕,並出現TypeError。 - 如果編譯失敗,則承諾將拒絕,並出現
WebAssembly.CompileError。 - 如果
source是一個拒絕的承諾,則承諾將拒絕,並出現錯誤。 - 如果
source的Result存在錯誤(例如 MIME 型別錯誤),則承諾將拒絕,並出現錯誤。
示例
流式編譯
以下示例(請參閱我們託管在 GitHub 上的 compile-streaming.html 演示,以及 現場檢視)直接從底層源流式傳輸 Wasm 模組,然後將其編譯為 WebAssembly.Module 物件。因為 compileStreaming() 函式接受 Response 物件的承諾,所以你可以直接將來自呼叫 fetch() 的承諾傳遞給它,而無需等待承諾實現。
js
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() 例項化生成的模組例項,並呼叫匯出的函式。
規範
| 規範 |
|---|
| WebAssembly Web API # dom-webassembly-compilestreaming |
瀏覽器相容性
BCD 表格僅在瀏覽器中載入