HTML5 Web Workers: Web Development

Published March 24, 2014
— File Photo
— File Photo

User Experience (UX) on the web has improved a lot over the past decade, thanks to fast machines, high speed data connections and upgraded browsers. But fast machines play their part mostly at the server end; the client side doesn’t really utilise their full potential. This lack of efficiency lies in the fact that browsers run JavaScript in a single-threaded environment, meaning multiple scripts cannot run at the same time. It doesn’t really matter if you have a multi-cored processor installed on your system or a simple one because your browser won’t be able to utilise its true power.

Every developer runs into a scenario where the web application he built so enthusiastically, is ruined because of obstructive JavaScript. The User Interface (UI) layer is blocked because of long running scripts; these scripts prevent the user to interact with action items that use JavaScript in order to function properly, such as an animated button etcetera. For example, imagine a site that needs to handle UI events, process large amounts of API data and manipulate the Document Object Model (DOM, which is part of the presentation layer). Unfortunately all of this cannot happen simultaneously, due to limitations in browsers' JavaScript runtime. In other words script execution is catered within a single thread.

Some of you might think that AJAX (Asynchronous JavaScript and XML) is the answer to this problem, but I’m sorry to burst your bubble because asynchronous events are processed after the current executing script has yielded. So how do we deal with this situation? Say hello to HTML5 web workers

Well don’t be confused, “Web Worker” is the name of one of the many taxonomies available in HTML5 specification. The WHATWG (Web Hypertext Application Technology Working Group) and World Wide Web Consortium (W3C) define HTML5 web worker as, “a JavaScript script executed from an HTML page that runs in the background, independently of other user-interface scripts that may also have been executed from the same HTML page..” How the Workers work!

Using the worker, developers can now run code containing extensive computations in the background, without worrying about the UI layer being blocked. Let’s have a closer look at how the workers make this possible. Take a look at the following HTML5 document:

HTML5 Document
HTML5 Document

The HTML5 markup shows the simplest use of a worker for performing a computationally expensive task without interrupting the user interface. In this example, the main document creates a worker to compute prime numbers, and display the most recently found prime number. The output of this document’s body is a single line of text which says “The highest prime number discovered so far is: ________ “. The dashed area is of course replaced by the result of the worker.

You must have noticed that there is no coding in this document. That is because a worker always works from an external JavaScript file, in this case “worker.js”. The content of the worker created in this file, is the following:

HTML5 Document 2
HTML5 Document 2

As you can see there is nothing out of the ordinary here, just plain old JavaScript used for computing the prime number, except for the postMessage() method. This method is used to send a message back to the HTML5 document whenever a prime number is found and the result section gets updated.

The use of a worker just to display a small line of text (on a webpage) might not be a good idea; but if you have been following closely you must have noticed that the script written to compute the prime numbers is going to execute itself till infinity. It will keep updating the result section with the newest found prime number till kingdom come, or the browser window is closed. If the same logic would have been used to achieve the same result, without using a worker, the browser window would have crashed in less than 30 seconds.

Restrictions and limitations

Now that you know how powerful HTML5 Web Workers are, let’s have a look at their limitations. Inside a worker script, we do not have access to many important JavaScript objects like document, window, console, parent and DOM. Yes! A worker is not allowed to access the DOM because of security reasons; but as I said this restriction only applies inside the worker script, which means we can still update the DOM with the results from the worker.

Although workers are denied access to some pretty important JavaScript objects, they are allowed to use important methods like setTimeout(), clearTimeout(), setInterval(), clearInterval(), navigator etcetera and most importantly we can use the HTML5 local storage and XMLHttpRequest objects inside our workers.

When to use them

A worker is best suited for situations where we have to deal with third-party APIs that force the main thread to wait for a result, before proceeding to the next statement. In such cases, we can delegate this task to a newly spawned worker to leverage its asynchronous capability to our benefit.

Tuts+, a blog which offers tutorials and technical articles, talks about how there might come a time when we need to process a huge amount of data returned by the server, as seen in the above example. Traditionally, processing such data negatively impacts the application's responsiveness, thereby making the UX unacceptable. A more elegant solution would be to divide the processing work among several workers to process non-overlapping portions of the data, thus taking multi-threading to the next level. Web workers also help in polling, where we continuously poll a destination in the background and post messages to the main thread when new data is received, making them a really smart choice.

Conclusion

HTML5 Web Workers have brought the power associated with multiple threads, in an otherwise single-threaded environment, out in the real world. All of the latest browsers support web workers including Firefox, Chrome, Safari, Opera and even Internet Explorer 10. The best part is that if you know how to write proper JavaScript, you are all set to make use of HTML5 Web Workers and if you’re not, then get yourself to it, because knowing how to write JavaScript is the key to HTML5 development.

The Writer is a User Interface Engineer at TRG Tech. Twitter: @khalidmajidali

Opinion

Editorial

Judiciary’s SOS
Updated 28 Mar, 2024

Judiciary’s SOS

The ball is now in CJP Isa’s court, and he will feel pressure to take action.
Data protection
28 Mar, 2024

Data protection

WHAT do we want? Data protection laws. When do we want them? Immediately. Without delay, if we are to prevent ...
Selling humans
28 Mar, 2024

Selling humans

HUMAN traders feed off economic distress; they peddle promises of a better life to the impoverished who, mired in...
New terror wave
Updated 27 Mar, 2024

New terror wave

The time has come for decisive government action against militancy.
Development costs
27 Mar, 2024

Development costs

A HEFTY escalation of 30pc in the cost of ongoing federal development schemes is one of the many decisions where the...
Aitchison controversy
Updated 27 Mar, 2024

Aitchison controversy

It is hoped that higher authorities realise that politics and nepotism have no place in schools.