WebAssembly 使用介绍

发布时间: 更新时间: 总字数:626 阅读时间:2m 作者: 分享 复制网址

WebAssembly 简称 wasm,是下一代 web 技术,实质是体积小且加载快的二进制(新的字节码)格式,目的是充分发挥硬件能力已达到原生执行效率。本文除介绍 wasm 外,还提供基于 golang/tinygo 的示例,示例涵盖htm、vue2、vue3、quasar的使用场景。

介绍

wasm 可以使用非 JavaScript 编程语言编写代码且能在浏览器上运行的技术方案。2019年12月5日,WebAssembly 正式成为 World Wide Web Consortium (W3C) 的标准,W3C 标准还包括:htmlcssJavaScritp

优点

  • 文件加载:体积小、速度快
  • 编译:提前编译
  • 解析:比 JavaScript 快
  • 执行:更快,WebAssembly 更接近与机器码
  • 垃圾回收:不直接回收垃圾
  • 安全:支持hash和签名等

用途

  • 视频音频编解码
  • 图形
  • 3D
  • 密码计算
  • 游戏
  • 便携式边缘计算

工作原理

JavaScritp/TypeScritp  ->  Converter  ->  *.js  -
                                                  \
                                                    -> Browser
                                                  /
Golang/Rust/C/C++/...  ->  Compiler  ->  *.wasm -

支持的语言

可以使用如下语音开发 wasm 模块:

  • Obj-C
  • Rust
  • Golang
  • Zig
  • AssemblyScript
  • C/C++
  • Swift

浏览器支持

查看浏览器是否支持 WebAssembly,浏览器开发者模式下,在 Console 中输入 WebAssembly 可以看到对应的输出:

> WebAssembly

示例

# 初始化
npm init wasm-app ./demo-wasm && cd demo-wasm && npm i

# 启动
npm start

# 访问,可以看到弹出的 alret 框
http://localhost:8080/

引用

fetch('module.wasm').then(response =>
  response.arrayBuffer()
).then(bytes =>
  WebAssembly.instantiate(bytes, importObject)
).then(results => {
  // Do something with the compiled results!
});

Golang 实现

Go 自 1.11 版本开始支持 wasm,Go 也可以通过 syscall/js 包调用 JavaScript 函数,和对 DOM tree 的操作。采用 tinygo 编译 wasm 包是 golang 编译包的 10% 左右。

demo 示例

go-wasm-demo 提供 wasm 基于 html、vue2、vue3、quasar 框架的 demo 示例:

  • demo-hello-world
  • demo-callback
  • demo-dom-tree
  • demo-fibonacci-number
  • demo-vue2
  • demo-vue3
  • demo-quasar2

扩展

  • GopherJS 也是一个可以将 Go 语言转换成 JavaScript 代码编译器。
  • 可以借助 go-git/go-git 实现通过浏览器加载 git 仓库和提交代码
  • 同理,也可以和 OSS 结合实现在线编辑 OSS 文件

参考

  1. https://webassembly.org/
  2. https://github.com/rustwasm
  3. https://mbebenita.github.io/WasmExplorer/
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数