What are Web Workers?

html5 web workers

What are Web Workers?

This article is all about making use of web workers and their importance in HTML5.Java script engine built up with a single thread, and there is no concurrent process behind them (No other process is executed until the first process gets finished) as javascript runs in the foreground and makes the web page time-consuming. Therefore, to avoid this hefty problem, HTML5 has come up with a new technology named Web workers. It’s a small background script that does computation at expensive tasks without intervening in the user interface or performance of the web page. This isolated thread is relatively lightweight and is supported in all web browsers. This makes HTML to start up additional threads.

Types of Web Workers in HTML5

Web workers are also termed as “dedicated workers”. They got a separate shared memory model. In other words, we can say an entire javascript scope happened to be run on a single thread. While working in a web browser, we have encountered some runway dialog message due to the heavy processing of the page. To provide a good solution, Web browser HTML API has come up with ruling different computations at the same time.

Three important types of Web workers are given below:

html5 web

1. Shared Web Worker

This type uses API, and each unit of worker has multiple connections while sending a message (multiple Scripts) provided each context is from the same origin. Browser Support for this worker is limited. They are called using a shared worker() constructor.

2. Dedicated Web Worker

Creating a file is very simple just by calling a Constructor with its source path. They make use of message communication called post message () method during message transfer. Even the event handlers Are used when some listener takes place. The handler onmessage() has been used to receive a message.

3. Service Worker

This worker doesn’t directly interact with the web page and runs in the background. They can restore whenever required and acts as a proxy, and multiple threads can access them.

How to Create a Web Workers File?

They do not have support to some features like window object, DOM, The parent object. All the functions are done by passing a replica of them. Popular Course in this categoryHTML Training (12 Courses, 19+ Projects, 4 Quizzes)12 Online Courses | 19 Hands-on Projects | 89+ Hours | Verifiable Certificate of Completion | Lifetime Access | | 4 Quizzes with Solutions
4.5 (6,492 ratings)Course Price
₹6999 ₹41999
View Course


Related CoursesBootstrap Training (2 Courses, 6+ Projects)XML Training (5 Courses, 6+ Projects)CSS Training (9 Courses, 9+ Projects)

Step 1: To create a file, import Worker () constructor A file is created using a new object, and the script looks like it.

var worker = new Worker(sample.js);

Step 2: Creation of post message (). The created worker files automatically call up the post message() method. The post message () methods direct the message passing to the main thread. And similarly, we can send a message from the main thread to the worker thread. By here, the worker Starts.

worker. postMessage();

Step 3: Next to throw the event handler to permit the message from the web worker.

worker. onmessage = function(event)

Henceforth we have seen how to send and receive messages, Now let’s see how to terminate the worker in the middle of the process.

Step 4: To stop the Process.

worker.terminate()

Step 5: To implement an error handling scenario worker uses.

Worker.onerror();

Top 9 Features

  1. Web workers being asynchronous protocol they were best suited for doing computational tasks and considered to be the professional features of Javascript.
  2. Web workers pay a strict execution platform for mobile and desktop windows, letting to run the web page without freezing up the web page in the browsers.
  3. The core benefit is we can run expensive processes within a single individual thread, which doesn’t interrupt the running main thread.
  4. Web-workers are small light-weighted threads that live individually, interleaving the user interface.
  5. Web-workers being kernel oriented threads helps in reaching out to the high performance of the browsers page.
  6. Web-workers help in creating parallel programming and performs multithreading actions.
  7. Web-workers enhances speed for java JScript application.
  8. Web-worker is considered to be a client-side script and used higher in games application.
  9. Web worker threads communicate with each other using the post Message () call-back method.

Examples of HTML5 Web Workers

Web workers have access to the navigator, XMLHTTP Request, Navigator due to their multi-processing activities. The below example focuses on dedicated workers types to demonstrate.

Example #1

Shows Sample Worker file Demonstrating the working of the browser.

Code:

<!DOCTYPE html>
<html>
<head>
<title>Web Worker Demo </title>
</head>
<body>
<h2>Validating the browser compatibility of Web Browsers</h2>
<div id="yes"></div>
<div id="No"></div>
<button onclick="worker_demo();"> Submit</button>
<script type="text/javascript">
function worker_demo()
{
if(typeof(Worker)!=="undefined"){
document.getElementById("yes").innerHTML=" Browser Supports";
}
else
{
document.getElementById("NO").innerHTML="Browser Not Supporting the workers";}
}
</script>
</body>
</html>

Output:

HTML5 Web Workers

Example #2

The following example shows how the worker tasks run behind the task using class, and the count is done for the worker tasks. The worker tasks automatically update the web page on every loop until the loop ends. To terminate the worker’s execution, terminate () has been used here.

The job is done behind the background by the web worker:

Code:

wrk.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Web Workers Demo</title>
<style type="text/css">
body {padding-top:18px;}
.output-cont {margin-left:12%; margin-top:28px;}
.output-cont h2 {width:150px; height:95%;}
.output-cont button {padding:3px 7px; font-size:1.3rem; font-family:sans-serif;  }
</style>
</head>
<body>
<div class="output-cont"><button onclick="testWork()">start worker</button><h2 id="wOutput"></h2><button onclick="stopWorker()">terminate </button></div>
<br/>
<div class="output-cont"><button onclick="test()">start blocking thread</button><h2 id="mainThreadOutput"></h2></div>
<br/>
<div class="output-cont"><button onclick="alert('page responsive!')">test responsiveness</button></div>
<script>
var worker;
function testWork() {
if (typeof(Worker) !== "undefined") {
if (typeof(worker) == "undefined") {
worker = new Worker("demo.js");
}
worker.onmessage = function(event) {
document.getElementById("wOutput").innerHTML = event.data;
};
} else {
document.getElementById("wOutput").innerHTML = "Web Workers are unsupported";
}
}
function stopWorker() {
worker.terminate();
worker = undefined;
}
function test() {
for (var j = 0; j < 20000; j++) {
document.getElementById("mainThreadOutput").innerHTML = "Main Thread Counter: " + j;
}
}
</script>
</body>
</html>
Next creating an separate external  javascript file demo.js and the code comes as shown.
demo.js
j = 0;
while (j < 200000)
{    postMessage("Web Worker Counter: " + j);
j++;
}

Output:

worker tasks
worker tasks

Conclusion

We have seen how web workers work independently from the main thread that helps web organizations make demanding apps. And it is strongly recommended to use web workers in javascript for heavy-weight tasks. It is suggested that when the web browser is no longer in use should be closed to consume the system resources.

Recommended Articles

This is a guide to HTML5 Web Workers. Here we discuss the types, top 9 features of HTML5 Web Workers and its Examples with Code Implementation. You can also go through our suggested articles to learn more –

  1. Html5 New Elements
  2. HTML Frames
  3. Advantages of HTML
  4. HTML5 Interview Questions

Leave a Comment

Your email address will not be published. Required fields are marked *