404 CHAPTER 9 Asynchronous operations
Lesson 2: Working with web workers
Another way to perform asynchronous operations is to use web workers. Web workers are
useful for execution of a script file in a background task. The worker can send messages to the
spawning task by posting messages to an event handler specified by the creator. Messages
can be any object that can be serialized. The worker thread doesn’t block the user interface
thread, so the UI remains fast and fluid.
After this lesson, you will be able to:
■■Describe web workers.
■■Implement asynchronous operations by using the web worker.
Estimated lesson time: 20 minutes
Web worker details
Web workers’ state is isolated from the webpage. When messages are posted to and from the
web worker, the message object is serialized. This creates a copy of the message, so the web
worker and the creator never reference the same object. Web workers also lack synchroniza-
tion locks, critical sections, semaphores, or mutexes. They don’t have access to the document
object model (DOM), so if you need to access the DOM, the web worker must post a mes-
sage back to the creator, and the creator must process the message and access the DOM as
needed.
It’s common to start a web worker, which creates its own event loop and waits for further
input. This is similar to a service, which starts and waits for input and doesn’t terminate after
processing input.
Consider the following HTML page that accepts input and has a button that sends the
input to a web worker. The web worker responds once for each character in the message sent,
returning the uppercase of the letter.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.8.2.js"></script>
<script src="default.js"></script>
</head>
<body>
<input type="text" id="message" value="Enter message here" /><br />
<button id="btnSend" type="button">Send Message</button><br />
<div id="result"></div>
</body>
</html>