HTML and CSS Reference
In-Depth Information
You can access navigator and location objects in the web-worker code. You can also use the
setTimeout()
,
setInterval()
,
clearTimeout()
, and
clearInterval()
methods in web workers.
n
Note
The
XMLHttpRequest
object is covered in Chapter 11. For the purpose of this chapter, it's sufficient to
know that
XMLHttpRequest
is an object that allows you to make requests (GET/POST) to server-side resources.
Instead of using the
$.ajax()
method you can use
XMLHttpRequest
object to call web methods, MVC action
methods, and generic handlers.
Using Web Workers
Now that you have a basic understanding of what web workers are and what they can do, let's convert the
web page from Listing 10-1 so that it doesn't block the UI. This essentially calls for running the processing
logic (
do
-
while
loop) in a worker thread, to free up the UI thread to handle user interactions. Listing 10-2
shows how this can be done.
Listing 10-2.
Creating a Web Worker
<script type="text/javascript">
var worker;
$(document).ready(function () {
$("#btnStart").click(function () {
worker = new Worker("scripts/processing.js");
worker.addEventListener("message", ReceiveMessageFromWorker, false);
worker.postMessage("Hello Worker!");
});
</script>
This code creates a global variable—
worker
—in a web form. This global variable is used to store the
web worker object you create in the button's
click
event handler. The
ready()
function wires the
click
event handler of
btnStart
. In the
click
event handler the code creates a new
Worker
object. The JavaScript
code that you wish to execute in a worker thread is placed in a separate script file. The path of the script
ile (
scripts/processing.js
) that includes the JavaScript code to be executed in the
Worker
is passed to the
constructor.
Although not mandatory, often you're interested in receiving the result of processing from the worker
thread so you know the outcome. The
message
event of the
Worker
object lets you listen to messages sent by
the worker thread. The
addEventListener()
method wires the
message
event to the
ReceiveMessageFromWorker()
function.
ReceiveMessageFromWorker()
is a developer-defined function and is
discussed shortly. The code then calls the
postMessage()
method of the
Worker
object.
postMessage()
acts
as a trigger for starting the worker thread. You can pass it input data as a parameter. Although the code
passes a string to the worker thread, the data can be in some other form such as a JSON object. If you don't
want to pass any data, you can simply pass an empty string.
ReceiveMessageFromWorker()
displays the result of processing as returned by the worker thread, like
this:
function ReceiveMessageFromWorker(evt) {
alert(evt.data);
}