Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WebAssembly #15

Open
gzqby opened this issue Jan 4, 2024 · 0 comments
Open

WebAssembly #15

gzqby opened this issue Jan 4, 2024 · 0 comments

Comments

@gzqby
Copy link
Owner

gzqby commented Jan 4, 2024

什么是WebAssembly

  • WebAssembly 是一种二进制编码格式,而不是一门新的语言。
  • WebAssembly 不是为了取代 JavaScript,而是一种补充(至少现阶段是这样),结合 WebAssembly 的性能优势,很大可能集中在对性能要求高(例如游戏,AI),或是对交互体验要求高(例如移动端)的场景。
  • C/C++ 等语言可以编译 WebAssembly 的目标文件,也就是说,其他语言可以通过编译器支持,而写出能够在浏览器前端运行的代码。

发展历史

从发展历史可以总结技术发展规律,如何从一个个人项目到W3C标准

截屏2024-01-04 16 44 30

从性能进一步探索前端方案:WebAssembly、Worker、JavaScript对比

为什么把worker拿出来,因为两者可以搭配使用

WebAssembly Worker JS
性能
安全性
生态丰富性
兼容性
适合任务 高性能、计算密集型任务 异步执行、耗时任务 快速开发、通用任务

eg用golang写wasm

  1. 安装golang环境
  2. 需要一些模版代码
// js胶水代码
cp "$(go env GOROOT)/misc/wasm/wasm_exec.js" .
// html模版代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="root"></div>
</body>
    <script src="wasm_exec.js"></script>
    <script>
    const go = new Go();
    WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject)
        .then((result) =>{
            go.run(result.instance)
        });
    </script>
</html>
  1. 写wasm代码
package main

import (
    "fmt"
    "syscall/js"
    "time"
)

// js可以调用的函数
func forJsFunc(this js.Value, args []js.Value) any {
    // duration := int(js.Value(args[0]).Int())
    duration := args[0].Int()
    var cb = args[len(args)-1]
    go func() {
        // time.Sleep(time.Second * duration)
        time.Sleep(time.Duration(duration) * time.Second)
        str := fmt.Sprintf("it's %d second", duration)
        cb.Invoke(js.ValueOf(str))
    }()

    return nil
}

func main() {
    done := make(chan int, 0)
    // js的golbal
    var jsGlobal = js.Global()
    // Set、Get对象等
    var document = jsGlobal.Get("document")
    var root = document.Call("getElementById", "root")
    root.Set("innerHTML", js.ValueOf("hello world!"))

    var alert = jsGlobal.Get("alert")
    // 执行
    alert.Invoke("alert")

    // 设置js的全局函数
    jsGlobal.Set("wamsFunc", js.FuncOf(forJsFunc))
    <-done
}

// 编译
GOARCH=wasm GOOS=js go build -o test.wasm main.go

Golang syscall/js 文档

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant