Understanding JavaScript Web Workers

Microsoft's recent Windows 8 announcement would seem to indicate that HTML5 and JavaScript will become a more important part of the future operating system. The announcement makes HTML5 and anything HTML5/JavaScript related an important subject for any Windows developer. To most developers HTML is a "tag" based user-interface specification. However, HTML5 is more than just new "tags". It's a number of new specifications that every browser will, eventually, implement. Yoked to, but separate from the HTML5 specification is a specification defining background running scripts called Web Workers.

Web Workers Overview

Unless an executing script periodically allows the user interface to process incoming events, it will block the user interface thread leaving the web application unresponsive. Though developers found creative ways around the issue, until Web Workers nothing formal existed for browsers to offload long running work. Below is a list of roles a Web Worker can play in a browser application.

  • Execute long running computationally intensive work
  • Background IO on a database or network connection
  • Coordinating work across multiple pages
  • Asynchronous work like stock ticker updates

A Web Worker simply runs a script file. Contents of the script file are up to the developer. Because of the overhead involved in starting a Web Worker, the recommendation is that the script should be some long running process. With some background on the Web Worker roles, focus turns to some sample code.

Web Worker Sample

Below is Web Worker code sample.

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        var worker = new Worker('runWorker.js');
        worker.onmessage = function (e) {
            txt.innerHTML = e.data;
        }
    </script>
    <title id="main">Web Worker</title>
</head>
<body>
<p id="txt"></p>
</body>
</html>

runWorker.js contains the code below.

var msg = 'Hello world!';
var n = 1;
while (true) {
    postMessage(msg);
 
    msg = 'Hello world!' + ' ' + ++n;
}

When executed, the sample ties up one of the processors on the machine executing the code as the while loop executes and repeatedly posts the latest "n" value. For security reasons the URL passed to the Web Worker constructor must share the same Scheme as the site. So, for example, if the Scheme includes https, then the URL must include https or like in the example the URL can be relative to the document.

Currently, some browsers have limited Web Worker support or, like Internet Explorer support Web Workers in a Community Technology Preview. The sample above works in the IE 10 Platform Preview. Developers can find the preview here. The graphic below depicts what is happening in the code above.

What's happening in the Web Worker sample code
Figure 1: What's happening in the Web Worker sample code

Web Workers live within a WorkerGlobalScope. WorkerGlobalScope provides a context and some supporting attributes described later in the article. Script code runs isolated in a separate Thread or Process (depending on the implementation). Web Workers leverage a new Web Messaging infrastructure outlined in a separate HTML5 Web Messaging specification. The remainder of the article will take a deeper dive into each of the components outlined above.

WorkerGlobalScope

The sample code demonstrates a Dedicated Web Worker. As the name would indicate, a Dedicated Web Worker is targeted for applications requiring point to point communication. The specification offers an alternative called Shared Web Worker for communication with multiple producers and consumers. A Shared Worker exposes more of the Messaging API components, but the underlying infrastructure is the same as a Dedicated Web Worker.

As stated earlier WorkerGlobalScope provides a sort of context for the Worker. Much of the infrastructure a developer leverages in a window/document has been carried to a Web Worker. So, for example, a WorkerGlobalScope includes Timer implementations. Each Web Worker implementation extends the WorkerGlobalScope to suit its needs.

Web Workers leverage a lot of the existing Eventing infrastructure. Web Workers also leverage a new Web Messaging Specification.

Web Messaging Infrastructure

Web Messaging more securely enables cross-document communication. Enabling Cross-site scripting opens a security hole in a browser. For security reasons cross-site scripting is disabled. Cross-document communication is important to building Web Applications, so Web Messaging has been architected for security as well as communication capability.

Web Messaging protocols pass around a MessageEvent object. In the example, "data" is the attribute containing the message payload; "data" is a string in the example, but can be any type.

Web Workers leverage the Web Messaging Channel Messaging infrastructure. A MessageChannel connects two MessagePorts. The specification refers to the setup as "entangling" the ports. A call to postMessage on a MessagePort puts data across the channel. Each MessagePort maintains a message queue. Messages posted on one port on the MessageChannel are set to the other port on the MessageChannel and visa-versa. MessagePorts receive a message via an "onmessage" function.

Web Workers extend the Web Messaging infrastructure supporting posting to an Array of MessagePorts. MessagePort Arrays are handy for multiple notifications.

Conclusion

Web Worker is a new specification outlining the behavior of JavaScript background workers. Web Workers leverage the upcoming HTML5 Web Messaging API.



About the Author

Jeffrey Juday

Jeff is a software developer specializing in enterprise application integration solutions utilizing BizTalk, SharePoint, WCF, WF, and SQL Server. Jeff has been developing software with Microsoft tools for more than 15 years in a variety of industries including: military, manufacturing, financial services, management consulting, and computer security. Jeff is a Microsoft BizTalk MVP. Jeff spends his spare time with his wife Sherrill and daughter Alexandra.

Related Articles

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Instead of only managing projects organizations do need to manage value! "Doing the right things" and "doing things right" are the essential ingredients for successful software and systems delivery. Unfortunately, with distributed delivery spanning multiple disciplines, geographies and time zones, many organizations struggle with teams working in silos, broken lines of communication, lack of collaboration, inadequate traceability, and poor project visibility. This often results in organizations "doing the …

  • Hurricane Sandy was one of the most destructive natural disasters that the United States has ever experienced. Read this success story to learn how Datto protected its partners and their customers with proactive business continuity planning, heroic employee efforts, and the right mix of technology and support. With storm surges over 12 feet, winds that exceeded 90 mph, and a diameter spanning more than 900 miles, Sandy resulted in power outages to approximately 7.5 million people, and caused an estimated $50 …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds