Loading the application in index.js

Create a new file in the /src directory named index.js and populate it with the following contents:

import WasmWorker from './WasmWorker.js';

/**
* If you add ?blob=true to the end of the URL (e.g.
* http://localhost:8080/index.html?blob=true), the worker will be
* created from a Blob rather than a URL. This returns the
* URL to use for the Worker either as a string or created from a Blob.
*/
const getWorkerUrl = async () => {
const url = new URL(window.location);
const isBlob = url.searchParams.get('blob');
var workerUrl = 'worker.js';
document.title = 'Wasm Worker (String URL)';

// Create a Blob instance from the text contents of `worker.js`:
if (isBlob === 'true') {
const response = await fetch('worker.js');
const results = await response.text();
const workerBlob = new Blob([results]);
workerUrl = window.URL.createObjectURL(workerBlob);
document.title = 'Wasm Worker (Blob URL)';
}

return Promise.resolve(workerUrl);
};

/**
* Instantiates the Wasm module associated with the specified worker
* and adds event listeners to the "Add" and "Subtract" buttons.
*/
const initializeWorker = async (wasmWorker, name) => {
await wasmWorker.initialize(name);
wasmWorker.addListenerForType('CALC_RESPONSE', payload => {
document.querySelector('#result').value = payload;
});

document.querySelector(`#${name}`).addEventListener('click', () => {
const inputs = document.querySelectorAll('input');
var [firstInput, secondInput] = inputs.values();
wasmWorker.calculate(+firstInput.value, +secondInput.value);
});
};

/**
* Spawns (2) workers: one associated with calc-add.wasm and another
* with calc-subtract.wasm. Adds an event listener to the "Reset"
* button to clear all the input values.
*/
const loadPage = async () => {
document.querySelector('#reset').addEventListener('click', () => {
const inputs = document.querySelectorAll('input');
inputs.forEach(input => (input.value = 0));
});

const workerUrl = await getWorkerUrl();
const addWorker = new WasmWorker(workerUrl);
await initializeWorker(addWorker, 'add');

const subtractWorker = new WasmWorker(workerUrl);
await initializeWorker(subtractWorker, 'subtract');
};

loadPage()
.then(() => console.log('%cPage loaded!', 'color: green;'))
.catch(error => console.error(error));

The application entry point is the loadPage() function. Before we dig into the worker initialization code, let's discuss the getWorkerUrl() function. Earlier in this section, we learned that you can pass a string representing a filename or a URL created from a Blob to the Worker() constructor. The following example code demonstrates the first technique:

var worker = new Worker('worker.js');

The second technique is demonstrated in the if (isBlob === 'true') block of the getWorkerUrl() function. If the current window.location value ends with ?blob=true, the URL passed to the Worker() constructor is created from a Blob. The only noticeable difference is the document.title value, which updates to reflect the URL type. Let's jump back to the loadPage() function to discuss the initialization code.

After an event listener is added to the Reset button in the loadPage() function, two WasmWorker instances are created: addWorker and subtractWorker. Each worker is passed to the initializeWorker() function as the wasmWorker argument. In initializeWorker(), the wasmWorker.initialize() function is called to instantiate the Wasm module. The wasmWorker.addListenerForType() function is called to set the value of the Result <input> to the value returned from the _calculate() function in the corresponding worker. Finally, an event listener is added to the click event of the <button> that either adds or subtracts the firstVal and secondVal <input> values (based on the name argument). That's it for the JavaScript code. Let's create an HTML and CSS file, then move on to the build step.

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

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