WebAssembly怎么选择DOM ?

各种文章、大V说WebAssembly时代要来了,Go、Rust、C++语言都可以写Web前端了。
我也想了解关注一下,但是找到的文章都在拼了命地夸WebAssembly的性能如何好,我就想问问:document.getElementById('xx')这句话用其他编程语言怎么写?

阅读 2.5k
2 个回答

写不了,WebAssembly现在操作不了dom(以后也未必能)
WebAssembly是用来解决js效率低的(需要复杂计算的函数可以用WebAssembly来写),不是替代js的

如果是rust的话, 有个web-sys的crate, 可以实现


use wasm_bindgen::prelude::*;

// Called by our JS entry point to run the example
#[wasm_bindgen(start)]
pub fn run() -> Result<(), JsValue> {
    // Use `web_sys`'s global `window` function to get a handle on the global
    // window object.
    let window = web_sys::window().expect("no global `window` exists");
    let document = window.document().expect("should have a document on window");
    let body = document.body().expect("document should have a body");
    
    // eg: 通过id获取dom 
    let _id_dom = document.get_element_by_id("loading").expect("should have #loading on the page")

    // Manufacture the element we're gonna append
    let val = document.create_element("p")?;
    val.set_text_content(Some("Hello from Rust!"));

    body.append_child(&val)?;

    Ok(())
}
推荐问题