HTML Web Workers: A web worker is a JavaScript running behind the scenes, without influencing the exhibition of the page.

The Web Workers are the separate JavaScript code which runs in the background of the web page without influencing the UI.


In this tutorial, you will learn-

What is a Web Worker?

When executing scripts in a HTML page, the page becomes lethargic until the script is done.

A web worker is a JavaScript that runs behind the scenes, freely of different scripts, without influencing the performance of the page. You can keep on doing whatever you desire: clicking, choosing things, and so forth, while the web worker runs behind the scenes.


HTML Web Workers Example

The example beneath creates a basic web worker that count numbers in the background:

Example

<!DOCTYPE html>
<html>
<body>

<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button> 
<button onclick="stopWorker()">Stop Worker</button>

<p><strong>Note:</strong> Internet Explorer 9 and earlier versions do not support Web Workers.</p>

<script>
var w;

function startWorker() {
  if(typeof(Worker) !== "undefined") {
    if(typeof(w) == "undefined") {
      w = new Worker("demo_workers.js");
    }
    w.onmessage = function(event) {
      document.getElementById("result").innerHTML = event.data;
    };
  } else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Workers...";
  }
}

function stopWorker() { 
  w.terminate();
  w = undefined;
}
</script>

</body>
</html>

Count numbers:

Note: Internet Explorer 9 and earlier versions do not support Web Workers.


Check Web Worker Support

Before creating a web worker, check whether the user’s browser support it:

if (typeof(Worker) !== "undefined") {
  // Yes! Web worker support!
  // Some code.....
} else {
  // Sorry! No Web Worker support..
}

Create a Web Worker File

Presently, let’s create our web worker in an outside JavaScript.

Here, we create a script that counts. The script is stored in the “demo_workers.js” file:

var i = 0;

function timedCount() {
  i = i + 1;
  postMessage(i);
  setTimeout("timedCount()",500);
}

timedCount();

The significant part of the code above is the postMessage() technique – which is used to post a message back on the HTML page.

Note: Normally web workers are not used for such basic scripts, but for more CPU intensive assignments.


Create a Web Worker Object

Since we have the web worker file, we need to call it from an HTML page.

The accompanying lines checks if the worker as of now exists, if not – it creates another web worker object and runs the code in “demo_workers.js”:

if (typeof(w) == "undefined") {
  w = new Worker("demo_workers.js");
}

Then, at that point we can send and receive messages from the web worker.

Add an “onmessage” occasion audience to the web worker.

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

At the point when the web worker posts a message, the code inside the occasion audience is executed. The data from the web worker is stored in event.data.


Terminate a Web Worker

At the point when a web worker object is created, it will keep on tuning in for messages (even after the outer script is done) until it is terminated.

To terminated a web worker, and free browser/computer assets, use the terminate() method:

w.terminate();

Reuse the Web Worker

In the event that you set the worker variable to undefined, after it has been terminated, you can reuse the code:

w = undefined;

Full Web Worker Example Code

We have effectively seen the Worker code in the .js file. Below is the code for the HTML page:

Example

<!DOCTYPE html>
<html>
<body>

<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>

<script>
var w;

function startWorker() {
  if (typeof(Worker) !== "undefined") {
    if (typeof(w) == "undefined") {
      w = new Worker("demo_workers.js");
    }
    w.onmessage = function(event) {
      document.getElementById("result").innerHTML = event.data;
    };
  } else {
    document.getElementById("result").innerHTML = "Sorry! No Web Worker support.";
  }
}

function stopWorker() {
  w.terminate();
  w = undefined;
}
</script>

</body>
</html>

Web Workers and the DOM

Since web workers are in external files, they don’t approach the accompanying JavaScript objects:

• The window object

• The report object

• The parent object


Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your projects with us.


0 Comments

Leave a Reply

Avatar placeholder