DEV Community

Cover image for Revolutionizing the Web with WebAssembly: A Comprehensive Guide
Cocoandrew
Cocoandrew

Posted on

Revolutionizing the Web with WebAssembly: A Comprehensive Guide

WebAssembly (Wasm) is a low-level binary format that is designed to be faster and more efficient than traditional JavaScript. It allows developers to run code on the web that is compiled from languages like C, C++, and Rust, and it can be run in web browsers and other environments that support the WebAssembly standard.

In this article, we will explore how to use WebAssembly in a web application. We will start by setting up a basic project, then we will write some simple C code and compile it to WebAssembly using the WebAssembly Binary Toolkit (WABT). Finally, we will write some JavaScript code to interact with our WebAssembly module.

Setting up the project

First, let's create a new project and install the dependencies we will need.

mkdir wasm-example
cd wasm-example
npm init -y
npm install --save-dev wasm-pack
Enter fullscreen mode Exit fullscreen mode

Next, let's create a simple C program that we will compile to WebAssembly. Create a file called src/main.c with the following contents:

#include <stdio.h>

int add(int a, int b) {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

This simple C function takes two integers as arguments and returns their sum.

To compile C code to WebAssembly (WASM), we will need to use a WASM compiler, such as emscripten. Emscripten is an open-source toolchain that allows developers to compile C and C++ code to WASM, as well as other target platforms such as JavaScript and OpenGL.
To use emscripten, we will need to install it and set up the necessary build tools. This can typically be done using a package manager such as Homebrew or apt-get, depending on the operating system:

$ brew install emscripten
$ emcc -v
Enter fullscreen mode Exit fullscreen mode

Once emscripten is installed, we can compile C code to WASM by running the emcc compiler with the C source file as input and the desired output file:

$ emcc hello.c -o hello.wasm

This will generate a WASM binary file (hello.wasm) that we can then use in our web application.

To run the WASM binary in the browser, we will need to create an HTML page with a JavaScript script that loads and runs the WASM file. Here is an example of how to do this:

Create a file called index.html with the following contents:

<!DOCTYPE html>
<html>
  <head>
    <title>WebAssembly Example</title>
  </head>
  <body>
    <script src="./index.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Next, create a file called index.js with the following contents:

const wasmUrl = "./pkg/main.wasm";

fetch(wasmUrl)
  .then((response) => response.arrayBuffer())
  .then((bytes) => WebAssembly.instantiate(bytes))
  .then((results) => {
    const { instance } = results;
    const { exports } = instance;

    console.log(exports.add(1, 2)); // 3
  });
Enter fullscreen mode Exit fullscreen mode

This JavaScript code loads the main.wasm file using the fetch API, then it uses the WebAssembly.instantiate function to parse the binary and create an instance of the WebAssembly module. The instance.exports object contains the functions and variables that are exposed by the WebAssembly module, and we can call them just like any other JavaScript functions.

In this case, we are calling the add function and printing the result to the console.

Application

WebAssembly can be used in a wide range of web applications, including:

  • Games: WebAssembly can be used to improve the performance of games and other graphics-intensive applications.

  • Data-intensive applications: WebAssembly can be used to improve the performance of applications that require a lot of data processing, such as data analysis or machine learning.

  • Web-based tools: WebAssembly can be used to create web-based versions of desktop tools, such as image editors or CAD software.

  • Mobile web applications: WebAssembly can be used to create web applications that have the performance and capabilities of native mobile apps.

  • Virtual reality and augmented reality applications: WebAssembly can be used to improve the performance and capabilities of VR and AR applications in the browser.

Advantages

There are several advantages to using WebAssembly in your web applications:

  • Improved performance: WebAssembly is designed to be faster and more efficient than JavaScript, which means that it can offer a significant performance boost for certain types of code. This can be especially useful for applications that require a lot of processing power, such as games or data-intensive applications.

  • Language interoperability: Because WebAssembly is a compilation target for many different languages, it allows developers to use the language that is best suited for a particular task. For example, developers can use C++ for performance-critical parts of an application and JavaScript for the rest.

  • Smaller file sizes: WebAssembly modules are typically smaller than their equivalent JavaScript counterparts, which can help reduce the size of your application and improve load times.

  • Improved security: WebAssembly is designed to be safer than JavaScript, with features like memory isolation and an explicit memory model that make it more difficult for attackers to exploit vulnerabilities.

  • Better support for legacy code: If you have an existing codebase written in a language like C++, you can use WebAssembly to bring that code to the web without having to rewrite it from scratch.

Overall, WebAssembly offers developers a powerful tool for improving the performance, security, and interoperability of their web applications.

Conclusion

In conclusion, WebAssembly is a powerful tool for running fast, efficient code on the web. It allows developers to use languages like C, C++, and Rust to write code that can be run in the browser, and it can be used in conjunction with JavaScript to create rich, interactive web applications.

By following the steps in this article, you should now have a basic understanding of how to use WebAssembly in a web application. There are many more advanced features and possibilities with WebAssembly, so be sure to explore the documentation and other resources to learn more.

Top comments (21)

Collapse
 
blindfish3 profile image
Ben Calder

What's the current situation with the interface between wasm and browser?

Last I heard this was a significant bottleneck that meant that, in practice, any performance gains in the wasm code were lost. In fact I remember a colleague converting some JS code to wasm that resulted in worse performance because of this.

That was a few years ago though, so I would hope this issue has improved.

Collapse
 
cocoandrew profile image
Cocoandrew

With recent advancements in the WASM browser interface, WASM is now a practical platform for creating high-performance applications that can run directly in the web browser. It has improved over the years and reduced the need for complex JavaScript glue code. Despite this, WASM may not always be the best option for all user situations, so it is still crucial for you to carefully examine the performance consequences before using it. I hope this answers your question ( :

Collapse
 
garyk2015 profile image
garyk2015

Exactly not to mention any calls to external APIs, DB read/writes.

You know in the real world it isn't just pure logic that can be optimized with asm.

And 'Revolutionize'? The majority of websites dont need cpu intensive calcs to run its just displaying text and graphics.

Collapse
 
cocoandrew profile image
Cocoandrew

Thanks for pointing out the inconsistencies in my previous answer. You are correct that I have not provided any evidence or examples to support claims that WASM improves security or interoperability. In terms of security, WASM offers some security advantages compared to traditional JavaScript-based web applications. For example, WASM modules run in a sandbox environment that prevents them from accessing sensitive data or executing malicious code, and WASM also has memory security features that prevent memory corruption and buffer overflows. However, it is important to note that WASM is not a panacea for web security and developers should still take reasonable precautions when building applications to guard against potential vulnerabilities.
In terms of interoperability, WASM is designed as a universal runtime environment that can be used to run code written in any programming language. This means developers can use WASM to create applications that run on any device with a modern web browser, regardless of the underlying operating system or hardware. This can make it easier for developers to create apps that are compatible with a variety of devices and platforms.
Again, my apologies for the lack of evidence and examples to back up these claims in my previous answer. I hope this clarification helps provide a more accurate and complete understanding of the security and interoperability benefits of WASM.

Collapse
 
olusoji_adebanke_009cf4fb profile image
Olusoji Adebanke

This was so helpful thank you!!!!

Collapse
 
stanleydave profile image
Stanley

Easy explanation well scripted

Collapse
 
user_741b33494c profile image
user_741b33494c

This is really nice. Weldon dear

Collapse
 
xannyberry profile image
XannyBerry

This explanation is very nice, simple and detailed. Very helpful for someone new to coding and tech. Keep it up

Collapse
 
juwon_emmanuel_a62f3d87f45 profile image
Juwon Emmanuel

This is really impressive and well documented

Collapse
 
okotieefe profile image
Okotie Abibat

Can it be used with rust

Collapse
 
stanleydave profile image
Stanley

since Rust is a programming language similar to C++ it can technically be used with it or one can compile it to WASM

Collapse
 
cocoandrew profile image
Cocoandrew

yes it can

Collapse
 
mohammed_dabo_c2a0a506061 profile image
Mohammed Dabo

This was very insightful

Collapse
 
obasi042 profile image
Obasi Nwosu

How does WebAssembly fit into the broader landscape of web technologies and the future of the web, and what impact do you think it will have on the industry as a whole

Collapse
 
stanleydave profile image
Stanley

WASM is likely to play a key role in the evolution of the web. It will enable the development of new types of web applications and experiences that are more powerful, efficient, and performant than what is currently possible with JavaScript and other technologies.

Collapse
 
mimisan profile image
Tech reven

Seeing this for the first time , please can you share links to other resources

Collapse
 
suxin2017 profile image
suxin2017 • Edited

I wrote an AST parser for CSS using RUST and it can run on the browser via WASM and here is it link
wasm rust

Collapse
 
mrjay_don_39157331cd9b08 profile image
Mr Jay Don

Great explanation.

Collapse
 
pretty_me_79f58df236ea496 profile image
Pretty Me

Great job!

Collapse
 
monjai profile image
mon-jai • Edited

One liner version:

const { instance: { exports } } = results;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mimisan profile image
Tech reven

Thank you, this was really helpful