WebAssembly.compileStreaming()

Baseline 廣泛可用 *

此功能已成熟,並可在多種裝置和瀏覽器版本上執行。自 2021 年 9 月起,所有瀏覽器均已支援此功能。

* 此特性的某些部分可能存在不同級別的支援。

WebAssembly.compileStreaming() 靜態方法直接從流式底層源編譯 WebAssembly.Module。如果需要在例項化之前編譯模組(否則應使用 WebAssembly.instantiateStreaming() 函式),此函式非常有用。

注意: 具有嚴格 Content Security Policy (CSP) 的網頁可能會阻止 WebAssembly 編譯和執行模組。有關允許 WebAssembly 編譯和執行的更多資訊,請參閱 script-src CSP

語法

js
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 或解析為 ResponsePromise,則該 Promise 會因 TypeError 而拒絕。
  • 如果編譯失敗,則 Promise 會因 WebAssembly.CompileError 而拒絕。
  • 如果 source 是一個拒絕的 Promise,則 Promise 會因該錯誤而拒絕。
  • 如果 sourceResult 有錯誤(例如,MIME 型別錯誤),則 Promise 會因錯誤而拒絕。

示例

編譯流式傳輸

以下示例(請參閱 GitHub 上的 compile-streaming.html 演示,並 即時檢視)直接從底層源流式傳輸 Wasm 模組,然後將其編譯為 WebAssembly.Module 物件。因為 compileStreaming() 函式接受一個 Response 物件的 Promise,所以您可以直接將其傳遞給呼叫 fetch() 獲得的 Promise,而無需等待 Promise fulfilled。

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() 例項化結果模組例項,並呼叫匯出的函式。

啟用 JavaScript 內建函式和全域性字串匯入

此示例在使用 compileStreaming() 編譯 Wasm 模組時啟用 JavaScript 字串內建函式和匯入的全域性字串常量,然後在用 instantiate() 例項化然後執行匯出的 main() 函式(該函式將 "hello world!" 記錄到控制檯)之前。 即時檢視其執行效果

js
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

瀏覽器相容性

另見