WebAssembly.compile()
Baseline 廣泛可用 *
WebAssembly.compile() 靜態方法將 WebAssembly 二進位制程式碼編譯成一個 WebAssembly.Module 物件。如果需要在例項化之前編譯模組,此函式非常有用(否則,應使用 WebAssembly.instantiate() 函式)。
注意: 具有嚴格 Content Security Policy (CSP) 的網頁可能會阻止 WebAssembly 編譯和執行模組。有關允許 WebAssembly 編譯和執行的更多資訊,請參閱 script-src CSP。
語法
WebAssembly.compile(bufferSource)
WebAssembly.compile(bufferSource, compileOptions)
引數
bufferSource-
一個包含您要編譯的 Wasm 模組的二進位制程式碼的 型別化陣列 或
ArrayBuffer。 compileOptions可選-
一個包含編譯選項的物件。屬性可以包括:
builtins可選-
一個包含一個或多個字串的陣列,這些字串允許在編譯後的 Wasm 模組中使用 JavaScript 內建函式。這些字串定義了您想啟用的內建函式。目前唯一可用的值是
"js-string",它啟用 JavaScript 字串內建函式。 importedStringConstants可選-
一個字串,指定 匯入的全域性字串常量 的名稱空間。如果您希望在 Wasm 模組中使用匯入的全域性字串常量,則需要指定此屬性。
返回值
一個 Promise,它解析為一個表示已編譯模組的 WebAssembly.Module 物件。
異常
- 如果
bufferSource不是 型別化陣列 或ArrayBuffer,則 Promise 會以TypeError拒絕。 - 如果編譯失敗,Promise 會以
WebAssembly.CompileError拒絕。
示例
使用 compile
下面的示例使用 compile() 函式編譯載入的 simple.wasm 位元組碼,然後使用 postMessage() 將其傳送到 worker。
const worker = new Worker("wasm_worker.js");
fetch("simple.wasm")
.then((response) => response.arrayBuffer())
.then((bytes) => WebAssembly.compile(bytes))
.then((mod) => worker.postMessage(mod));
注意:在大多數情況下,您可能需要使用 WebAssembly.compileStreaming(),因為它比 compile() 更高效。
啟用 JavaScript 內建函式和全域性字串匯入
此示例在透過 compile() 編譯 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
};
fetch("log-concat.wasm")
.then((response) => response.arrayBuffer())
.then((bytes) => WebAssembly.compile(bytes, compileOptions))
.then((module) => WebAssembly.instantiate(module, importObject))
.then((instance) => instance.exports.main());
規範
| 規範 |
|---|
| WebAssembly JavaScript 介面 # dom-webassembly-compile |
瀏覽器相容性
載入中…