Are browsers no longer able to run C/C++, Go... JavaScript?

Are browsers no longer able to run C/C++, Go... JavaScript?

Daily short news for you
  • For a long time, I have been thinking about how to increase brand presence, as well as users for the blog. After much contemplation, it seems the only way is to share on social media or hope they seek it out, until...

    Wearing this shirt means no more worries about traffic jams, the more crowded it gets, the more fun it is because hundreds of eyes are watching 🤓

    (It really works, you know 🤭)

    » Read more
  • A cycle of developing many projects is quite interesting. Summarized in 3 steps: See something complex -> Simplify it -> Add features until it becomes complex again... -> Back to a new loop.

    Why is that? Let me give you 2 examples to illustrate.

    Markdown was created with the aim of producing a plain text format that is "easy to write, easy to read, and easy to convert into something like HTML." At that time, no one had the patience to sit and write while also adding formatting for how the text displayed on the web. Yet now, people are "stuffing" or creating variations based on markdown to add so many new formats that… they can’t even remember all the syntax.

    React is also an example. Since the time of PHP, there has been a desire to create something that clearly separates the user interface from the core logic processing of applications into two distinct parts for better readability and writing. The result is that UI/UX libraries have developed very robustly, providing excellent user interaction, while the application logic resides on a separate server. The duo of Front-end and Back-end emerged from this, with the indispensable REST API waiter. Yet now, React doesn’t look much different from PHP, leading to Vue, Svelte... all converging back to a single point.

    However, the loop is not bad; on the contrary, this loop is more about evolution than "regression." Sometimes, it creates something good from something old, and people rely on that goodness to continue the loop. In other words, it’s about distilling the essence little by little 😁

    » Read more
  • Alongside the official projects, I occasionally see "side" projects aimed at optimizing or improving the language in some aspects. For example, nature-lang/nature is a project focused on enhancing Go, introducing some changes to make using Go more user-friendly.

    Looking back, it resembles JavaScript quite a bit 😆

    » Read more

Issues

I used to wonder if browsers could run languages other than JavaScript, such as Python or Golang. Because we all know that JavaScript has been the dominant language in browsers for a long time, it is the primary language for interacting with browser components.

JavaScript is powerful, but it also has its drawbacks. It consumes a lot of memory and can struggle with heavy computational tasks, causing the main thread to freeze and making user interactions with web pages terrible.

Nowadays, as user experiences have evolved, especially with the emergence of VR and NFT applications, websites need to handle more. JavaScript is currently able to handle this, but it is time for us to have new tools to support it.

Introduction to WebAssembly

What is WebAssembly?

WebAssembly (WASM) is a binary instruction format that runs in browsers or on servers. It is designed for performance and security. WebAssembly can be compiled from other programming languages such as C/C++, C#, Rust, Go, and many others.

What can WebAssembly do?

WebAssembly is used to execute heavy and computationally intensive tasks of web applications. This allows JavaScript to focus on handling the interactive aspects of the browser while letting WebAssembly handle the heavy lifting. WASM was initially created for the web, and it has many use cases such as image/video editing, gaming, VR, simulation on the web platform, and more.

Will WebAssembly replace JavaScript?

No! Or at least, it cannot replace JavaScript yet. As mentioned earlier, WebAssembly replaces JavaScript for CPU-intensive tasks, but JavaScript still cannot be replaced for user interaction.

The future of WebAssembly

Although WASM is still relatively new, with the development of current websites, the search for an optimization tool, WASM is becoming a promising candidate. WASM has been and is being used by applications like AutoCad and Figma for a long time. Let's look forward to the future advancements of WebAssembly.

Using WebAssembly

WebAssembly supports various programming languages. You can see a list at https://webassembly.org/getting-started/developers-guide/.

To use WebAssembly, the code of other programming languages is compiled into the binary format with the .wasm extension. Then, import the file into HTML code and start using the modules you have written. The following example demonstrates how to write a module in Go and use it with WebAssembly.

First, create a file named hello.go with a simple main function that prints "Hello, WebAssembly":

package main

import "fmt"

func main() {
  fmt.Println("Hello, WebAssembly!")
}

Then, build the file into the .wasm format for browser usage:

$ GOOS=js GOARCH=wasm go build -o main.wasm

To run the .wasm file in the browser, you need to use a .js file for support. For Golang, you can find it at:

$ cp "$(go env GOROOT)/misc/wasm/wasm_exec.js" .  

Now, create an index.html file to use wasm:

<html>
<head>
  <meta charset="utf-8" />
  <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>
</head>
<body></body>
</html>

Then, run an HTTP server. Here, I will use the http-server package:

$ http-server .  

Access http://127.0.0.1:8080 in your browser, and you will see "Hello, WebAssembly!" printed in the console.

Let's add a function to calculate the sum of two numbers in Golang and call it from JavaScript:

package main

import "syscall/js"

func main() {
	js.Global().Set("wasmAdd", js.FuncOf(add))
	<-make(chan bool)
}

func add(this js.Value, args []js.Value) interface{} {
	return args[0].Int() + args[1].Int()
}

syscall/js is the Go library that supports WebAssembly. I created an add function that returns the sum of two parameters.
js.Global().Set("wasmAdd", js.FuncOf(add)) is used to set the Go add function as the wasmAdd function to be used in JavaScript.
<-make(chan bool) prevents the Go program from exiting when it finishes executing.

Now, recompile the .wasm module using the steps above. Refresh the browser, and from the console window, call the wasmAdd(1,2) function:

wasmAdd(1,2)

It's that simple, isn't it!

Conclusion

WebAssembly is a portable binary instruction format that runs in browsers or on servers. WebAssembly can be compiled from other programming languages such as C/C++, C#, Rust, Go, and many others.

WebAssembly is used to execute heavy and computationally intensive tasks of web applications. It was not created to replace JavaScript.

Premium
Hello

Me & the desire to "play with words"

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.

Comments (3)

Leave a comment...
Avatar
Tiến Đức3 years ago

Assem vẫn còn chưa phổ biến lắm

Reply
Avatar
Trịnh Thị Anh3 years ago

Có hướng dẫn với python không ah?

Reply
Avatar
Xuân Hoài Tống3 years ago

Hiện tại có vẻ như Python vẫn chưa chính thức hỗ trợ cho ưebassembly. Tuy nhiên có một số thư viện không chính thức đã được phát hành bạn có thể tìm hiểu thêm xem sao!

Avatar
Ẩn danh3 years ago

Bạn ra thêm bài viết về webassembly đi mình cũng đang tìm hiểu cái này

Reply
Avatar
Xuân Hoài Tống3 years ago

B cần tìm hiểu thêm gì mình sẽ nghiên cứu thêm