HTML5 Web Workers

html5 web workers

HTML5 Web Workers play a crucial role in reducing the load on main execution thread of browser there by increasing performance. Web Workers are the simple means of running tasks in the background without interfering with user interface. In this article we are going to learn about html5 web workers so let’s get started.

Background of JavaScript Engine :

JavaScript Engine is known for executing single thread at once. Due to this reason there is a slowness in execution context for big websites which means processing large amount of data, handling more requests, executing many files will be harder and slower. Web Workers will be concatenated to the execution context as an external thread and process the requests needed in a separate execution context without interfering the actual JavaScript processing flow. With Web Workers JavaScript can be used as a multi threaded based environment.

Introduction to Web Workers :

Web Worker is basically a JavaScript Object created using a Constructor. Worker code will be run in a separate global context different from current window. One important thing to note here is we cannot perform DOM operations with a worker. Data transfer between worker and browser will be happened through events. New workers can also be spawned from the current worker if the hosted origin from parent is different with the current.

Web Workers Types:

There are two kinds of workers and they are :

  • Dedicated Workers
  • Shared Workers

What are Dedicated Workers ?

As per the name we can say that this type of workers are dedicated resources of the specific script. Dedicated Worker is basically invoked when it is called specifically by the script.

What are Shared Workers ?

Shared workers are invoked or accessed by multiple scripts from different execution contexts but the origin is same. Sometimes shared workers cannot communicate with events if the window type is different. For Example, If we are spawning a shared worker and we need to communicate with it from an incognito window then communication will fail. This problem is happening only on Firefox as noticed and all other browsers will work fine as per the current statistics.

Browser Support :

Web Workers are supported in all major browsers without any issues. In this article we are creating a web worker based on HTML5 and we are giving insight on Dedicated Worker only. For Shared Worker, you can refer to this awesome article from Mozilla – Using Web Workers

Before starting we can quickly check if our browser is supported or not with the following code :

										
											if (typeof(Worker) !== "undefined") {
											  console.log("Hurray, We have web worker support");
											} else {
											  console.log("Sorry, Web workers are not supported");
											}
										
									

Creating a Web Worker JS File :

Now, let’s start by writing our worker code in an external JS file. Let’s name that file with firstWorker.js

										
											var i = 0;
											function executeForLoop() {
												for(var j=0;j<500000;j++){
													i += j;
												}
												postMessage(i);
											}

											executeForLoop();
										
									

Above code is having a For Loop with 500000 iterations and adding every value of j to i and posts message back once execution completes in For loop.

Spawning a Web Worker :

As we already know that a worker is created by a constructor, let’s get started with it.

										var firstWorker = new Worker('firstWorker.js');
									

Now, let’s go ahead and add an event listener to send and receive messages from the worker.

										
											firstWorker.onmessage = function(event){
												document.getElementById("result").innerHTML = event.data;
											};
										
									

In worker file we need to keep following code to send the message.

										
											onmessage = function(e) {
												postMessage(e.result);
											}
										
									

One important point to note here is that the data between main thread and the worker is either copied or transfered but not shared.

Terminating a Web Worker :

When a worker is initiated, it will listen to the events until we terminate it. Below is the format used for terminating a worker.

										firstWorker.terminate();
									

Can we Re-Use the Worker after termination ?

Yes. We can still re-use the same worker by setting its value to undefined.

Importing Scripts using Worker :

Workers have access to the global function importScripts() with which we can import whatever script we need in a separate thread execution context.

For example:

										importScripts('filename.js');
									

Above code will import the mentioned file in a separate execution context. With this concept it is easier to load all the less critical JavaScript files in a separate thread which will basically reduce the load on main thread and execution will complete faster and site loading speed will be increased significantly.

Note: There is no specific order to execute scripts. They are processed in any order synchronously.

Final Touch :

Web workers are easy to operate and function. Since, worker cannot access DOM we don’t really need to worry about safety and concurrency of the worker thread and it’s communication with main thread. workers are designed to load JavaScript files asynchronously which will drastically improve the performance of page since we are loading all the less critical files in a different thread by reducing load on main thread. With the worker, we can even hit an ajax request but in a native JavaScript way by using XMLHttpRequest. Navigator object is also accessible to the worker. The only main thing is we cannot directly manipulate the DOM with the worker.

For more information on worker functions and interfaces, see Functions and Interfaces available to workers.

We will be bringing up more information on updates to html5 web workers soon.

web workers html5 are the most efficient concept to increase performance and reduce load on main execution thread. Since, web workers html5 are easy to use so please give it a try and let us know your thoughts.

Hope you like the article. Thanks for Reading !!!