Let's create a really simple application that gets the user's name and passes it to a web worker. The web worker will return a "hello" message back to the application. The code for this section can be found in Chapter 9/example9.1
.
First we create an application with webWorkerApp.html
, webWorkerApp.css
, and webWorkerApp.js
files. We add a text input field to the HTML asking for the user's name and a response section to display the message from the worker:
<div id="main"> <div> <label for="your-name">Please enter your name: </label> <input type="text" id="your-name"/> <button id="submit">Submit</button> </div> <div id="response" class="hidden"> The web worker says: <span></span> </div> </div>
In webWorkerApp.js
, when the user clicks on the submit button we call the executeWorker()
method:
function executeWorker() { var name = $("#your-name").val(); var worker = new Worker("helloWorker.js"); worker.addEventListener("message", function(event) { $("#response").fadeIn() .children("span").text(event.data); }); worker.postMessage(name); }
First we get the name the user entered into the text field. Then we create a new Worker
that has its code defined in helloWorker.js
. We add a message event listener that gets a message back from the worker and puts it into the page's response section. Last but not least we send the user's name to the worker using postMessage()
to start it.
Now let's create the code for our web worker in helloWorker.js
. There we add the code to get the message from the main thread and send a message back:
self.addEventListener("message", function(event) { sayHello(event.data); }); function sayHello(name) { self.postMessage("Hello, " + name); }
First we add an event listener to get the message from the application. We extract the name from the event.data
field and pass that into the sayHello()
function. The sayHello()
function simply prepends "Hello" to the user's name and sends the message back to the application using postMessage()
. Back in the main application it gets the message and displays it on the page.
18.191.102.112