pFad - Phone/Frame/Anonymizer/Declutterfier! Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

URL: http://developer.mozilla.org/zh-CN/docs/WebAssembly/Reference/JavaScript_interface/compile_static

7c-4bdf-a490-390a1aebf6dd/airgap.js" >

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

WebAssembly.compile()

基线 广泛可用 *

自 2017年10月 起,此特性已在主流浏览器中得到支持,可在大多数设备和浏览器版本中正常使用。

* 此特性的某些部分的支持程度可能有所不同。

WebAssembly.compile() 静态方法将 WebAssembly 二进制代码编译为一个 WebAssembly.Module 对象。如果在实例化模块之前必须要对其进行编译,那么这个函数很有帮助(否则,应该使用 WebAssembly.instantiate() 函数)。

备注:有严格内容安全策略(CSP)的网页可能会阻止 WebAssembly 编译和执行模块。与允许 WebAssembly 编译和执行有关的额外信息,参见 script-src CSP

语法

js
WebAssembly.compile(bufferSource)
WebAssembly.compile(bufferSource, compileOptions)

参数

bufferSource

一个类型化数组ArrayBuffer,包含你想编译的 Wasm 模块的二进制代码。

compileOptions 可选

一个编译选项的对象。属性包括:

builtins 可选

一个由一个或多个字符串组成的数组,用于在编译的 Wasm 模块中启用 JavaScript 内置功能。字符串定义你想启用的内置功能。当前,唯一可用的值是 "js-string",启用的是 JavaScript 字符串内置功能。

importedStringConstants 可选

一个字符串,为导入的全局字符串常量指定命名空间。如果你希望在 Wasm 模块中使用导入的全局字符串常量,就需要指定这个属性。

返回值

一个 Promise,兑现为表示已编译模块的 WebAssembly.Module 对象。

异常

示例

使用编译

下面的例子使用 compile() 函数编译加载的 simple.wasm 字节码,然后使用 postMessage() 将其发送给一个 worker

js
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!")。查看其在线版本

js
const importObject = {
  // 常规导入
  m: {
    log: console.log,
  },
};

const compileOptions = {
  builtins: ["js-string"], // 启用 JavaScript 字符串内置功能
  importedStringConstants: "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 Interface
# dom-webassembly-compile

浏览器兼容性

参见

pFad - Phonifier reborn

Pfad - The Proxy pFad © 2024 Your Company Name. All rights reserved.





Check this box to remove all script contents from the fetched content.



Check this box to remove all images from the fetched content.


Check this box to remove all CSS styles from the fetched content.


Check this box to keep images inefficiently compressed and original size.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy