Home arrow HTML arrow Page 2 - HTML 5 and Javascript Web Workers
HTML

HTML 5 and Javascript Web Workers


HTML and JavaScript let you do some amazing things, and continue to add new abilities all the time. One of these is a new breed of JavaScript objects called web workers. While they have certain limitations, they let you execute multiple JavaScript processes in parallel. This article series will show you how to use them in your web applications.

Author Info:
By: Alejandro Gervasio
Rating: 5 stars5 stars5 stars5 stars5 stars / 4
February 22, 2011
TABLE OF CONTENTS:
  1. · HTML 5 and Javascript Web Workers
  2. · Building a simple web worker

print this article
SEARCH DEVARTICLES

HTML 5 and Javascript Web Workers - Building a simple web worker
(Page 2 of 2 )

One of the most engaging facets of web workers is the simplicity of its messaging API. The only elements required to interact with a web worker from a web page are a method called “postMessage()” and an event handler, named “onmessage.” Period.

It’s time to stop talking and show some functional code. So, take a close look at the following snippet. It shows in a nutshell how to employ the aforementioned messaging elements with a naive web worker: 

// display messages from the worker
function displayMessage(msg) {
    var section = document.getElementsByTagName('section')[0];
    if (section === null){return};
    var par = document.createElement('p');
    par.setAttribute('class', 'worker_message');
    par.appendChild(document.createTextNode(msg));
    section.appendChild(par);
}

// create the web worker
var worker = new Worker('worker1.js');

// get messages from the web worker
worker.onmessage = function(e) {
    displayMessage(e.data);
}

// send a couple of messages to the web worker
worker.postMessage('Hello worker 1, how are you doing?');
worker.postMessage('Things are pretty busy over here.');

Certainly, a few interesting things are happening here. First off, the above script defines a basic function called “displayMessage().” This is used by the main page to display on screen messages received from a web worker. Secondly (and here’s where you should pay close attention), the script creates a web worker. This process is reduced to creating an instance of the Worker class and passing to it the name of the JavaScript file where the worker resides.

Once the worker has been properly spawned, it’s necessary to set up a two-way channel to interact with it. Well, to get messages from the worker, the “onmessage” event handler is assigned to the object, while sending messages to it from the main page is accomplished via the “postMessage()” method. In this particular case, the page uses this method to dispatch a couple of trivial messages, but it’s possible to send out any number of them.

At this point, you've hopefully grasped how to handle a web worker via the aforementioned messaging API -- but the definition of its associated file still remains an enigma. Again, don’t worry; here it is:

(worker1.js)

// get messages from the main script
self.onmessage = function(e) {
    self.postMessage('Web worker 1 says... message received from main script is: ' + e.data);
}

// do some other stuff here

From the above code fragment, it’s clear to see that the web worker uses the same “onmessage” handler to get messages from the main script, and the “postMessage()” method to send data back to the page. That’s quite easy to follow, isn’t it?

To keep the example clear and uncluttered, this trivial worker only catches data from the main script and then responds accordingly. In a more realistic use case, however, the worker should perform additional tasks, which would be executed independently from the browser’s UI thread.

And now that you've learned the basics of how to create and interact with a web worker, it’s time to put all the pieces together and add the earlier main script to the HTML5 document previously defined, so that you can test the example and see how it functions.

This will be done below, so keep reading.

The web worker in action

As I said in the segment that you just read, below I included the full source code corresponding to the previous example. First, here’s the HTML5 document that interacts with the sample web worker:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Example using a single Web Worker</title>
<script>
// display messages from the worker
function displayMessage(msg) {
    var section = document.getElementsByTagName('section')[0];
    if (section === null){return};
    var par = document.createElement('p');
    par.setAttribute('class', 'worker_message');
    par.appendChild(document.createTextNode(msg));
    section.appendChild(par);
}

// create the web worker
var worker = new Worker('worker1.js');

// get messages from the web worker
worker.onmessage = function(e) {
    displayMessage(e.data);
}

// send a couple of messages to the web worker
worker.postMessage('Hello worker 1, how are you doing?');
worker.postMessage('Things are pretty busy over here.');  
</script>
<style>
body {
    padding: 0;
    margin: 0;
    background: #0c1e74;
    font: 0.8em Arial, Helvetica, sans-serif;
    color: #000;
}
h1 {
    font-weight: normal;
    font-size: 2.1em;
    color: #0c1e74;
}
h2 {
   font-weight: normal;
   font-size: 1.8em;
   color: #0c1e74;
}
p {
    margin: 0 0 15px 0;
}
#wrapper {
    width: 920px;
    margin: 0 auto;
    background: #fff;
}
header, section, footer {
    display: block;
    padding: 15px;
}
.worker_message {
    color: #00f;
}
</style>
</head>
<body>
<div id="wrapper">
    <header>
        <h1>Using JavaScript Web Workers</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
    </header>
    <section>
        <h2>Worker message section</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
    </section>
    <footer>
        <h2>Footer section</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p> 
    </footer>
</div>
</body>
</html>

And finally, here’s the definition of the file attached to the web worker:

(worker1.js)

// get messages from the main script
self.onmessage = function(e) {
    self.postMessage('Web worker 1 says... message received from main script is: ' + e.data);
}

// do some other stuff here

So far, so good. If at this time, you give the above example a try using your own browser (other than Internet Explorer, of course), you should get an outcome similar to the following:

Admittedly, neither the main script nor the worker have flashy, outgoing personalities, as they the dialog between them looks pretty robotic. Nevertheless, the example demonstrates how to put a single HTML5 web worker into action.

Of course, it’s perfectly possible to set up a main script that interacts simultaneously with several web workers. However, this use case will be discussed in depth in the upcoming tutorial. 

Final thoughts

In this first installment of the series, I provided you with a humble introduction to using HTML5 web workers. As you saw in the earlier example, establishing a two-way communication channel between the main web page and a single web worker is a fairly straightforward process, thanks to the use of the handy messaging API included with HTML5.

So far, I've shown you how to make the main page interact with only one web worker, which has been pretty interesting, indeed. It’s feasible, however, to build a web page capable of interacting with multiple web workers at the same time, which is much more exciting.

This is exactly the subject that I plan to cover in the next chapter of the series. So, if you’re interested in learning the full details of this process, don’t miss the next part! 


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
HTML ARTICLES

- Does HTML5 Need a Main Element?
- Revisiting the HTML5 vs. Native Debate
- HTML5: Not for Phone Apps?
- HTML5 or Native?
- Job Hunting? Freelancer.com Lists This Quart...
- HTML5 in the News
- Report: HTML5 Mobile Performance Lags
- The Top HTML5 Audio Players
- Top HTML5 Video Tutorials
- HTML5: Reasons to Learn and Use It
- More of the Top Tutorials for HTML5 Forms
- MobileAppWizard Releases HTML5 App Builder
- HTML5 Boilerplate: Working with jQuery and M...
- HTML5 Boilerplate Introduction
- New API Platform for HTML5

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials