Writing custom loading code

Emscripten's generated loading code provides helpful error handling. If you're using Emscripten's output in production, I would recommend that you include it to ensure you're handling errors correctly. However, we don't actually need all the code to utilize our Module. Let's write some much simpler code and test it out. First, let's compile our C file down to glue code with no HTML output. To do that, run the following command:

emcc with-glue.c -O3 -s WASM=1 -s USE_SDL=2 -s MODULARIZE=1 -o custom-loading.js

The -s MODULARIZE=1 compiler flag allows us to use a Promise-like API to load our Module. Once the compilation is complete, create a file in the /chapter-05-create-load-module folder named custom-loading.html and populate it with the following contents:

<!doctype html>
<html lang="en-us">
<head>
<title>Custom Loading Code</title>
</head>
<body>
<h1>Using Custom Loading Code</h1>
<canvas id="canvas"></canvas>
<script type="application/javascript" src="custom-loading.js"></script>
<script type="application/javascript">
Module({
canvas: (() => document.getElementById('canvas'))(),
})
.then(() => {
console.log('Loaded!');
});
</script>
</body>
</html>

The loading code is now using ES6's arrow function syntax for the canvas loading function, which reduces the lines of code required. Start your local server by running the serve command within the /chapter-05-create-load-module folder:

serve -l 8080

When you navigate to http://127.0.0.1:8080/custom-loading.html in your browser, you should see this:

Custom loading code running in the browser

Of course, the function we're running isn't very complex, but it demonstrates the bare-bones requirements for loading Emscripten's Module. We will examine the Module object in much greater detail in Chapter 6Interacting with JavaScript and Debugging, but for now just be aware that the loading process is different from WebAssembly, which we'll cover in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset