Horje
Learn HTML Web Workers API Code

Tips (Total 10)


# Tips-1) What is HTML Web Workers API

A web worker is a JavaScript running in the background, without affecting the performance of the page.

When executing scripts in an HTML page, the page becomes unresponsive until the script is finished.

A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.

Everyone wants a website or application which work fast and can execute multiple operations simultaneously without affecting the performance of the page. However, sometimes we experience some delay response or degraded performance of page while executing some large operations. So this problem can be solved using the Web Workers.

Web Workers are the multithreaded object which can execute multiple JavaScript in parallel without affecting the performance of the application or webpage.

Following are some key features of the Web Workers:

Tips: Before working with HTML Web Workers you must have knowledge of JavaScript as the Web Worker depends on JavaScript.

 

Types of Web Workers:

In HTML5 Web Workers are of two types:

The dedicated worker can be accessed by only one script which has called it. The dedicated worker thread end as its parent thread ends. Dedicated workers are only used by one or single main thread.

It can be shared by multiple scripts and can communicate using the port. Shared workers can be accessed by different windows, iframes or workers.

Note: In this section, we will use dedicated Web Workers.

Example of HTML Web Worker

    <!DOCTYPE html>  
    <html>  
    <head>  
      <title>Web Worker API</title>  
    </head>  
    <body>  
    <h2>Example to check the browser support of Web Workers</h2>  
    <div id="supported"></div>  
    <div id="unsupported"></div>  
    <button onclick="worker();">click me</button>  
    <script type="text/javascript">  
       function worker()   
       {  
        if(typeof(Worker)!=="undefined"){  
         document.getElementById("supported").innerHTML="Supporting the browser";  
          }  
         else  
          {  
          document.getElementById("unsupported").innerHTML="Not supporting";}  
       }  
    </script>  
    </body>  
    </html>  

Output should be:

Example of HTML Web Worker

# Tips-2) What types of browsers will support

The numbers in the table specify the first browser version that fully support Web Workers.


# Tips-3) How to work a HTML Web Workers

The example below creates a simple web worker that count numbers in the background:

Learn HTML Web Workers

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

index.html
Example: HTML
<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>

Output should be:

Learn HTML Web Workers

# Tips-4) How to check Web Worker Support

Before learning the web Workers first, we need to check about the browser support. So following is the code which checks whether your browser is supporting or not.

Learn Web Worker Support

Example to check the browser support of Web Workers
index.html
Example: HTML
<div id="supported"></div>  
<div id="unsupported"></div>  
<button onclick="worker();">click me</button>  
<script type="text/javascript">  
   function worker()   
   {  
    if(typeof(Worker)!=="undefined"){  
     document.getElementById("supported").innerHTML="Supporting the browser";  
      }  
     else  
      {  
      document.getElementById("unsupported").innerHTML="Not supporting";}  
   }  
</script>  

Output should be:

Learn Web Worker Support

# Tips-5) How to create HTML Web Worker File

Now, let's create our web worker in an external JavaScript.

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

Learn to create HTML Web Worker File

Just create a .js file where put java code. Thus create HTML Web Worker File. Then, use it Example: <script async src="/script.js"></script> See Following example
Example: SCRIPT.JS
var i = 0;

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

timedCount(); 


# Tips-6) How to Create a Web Worker Object

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

The following lines checks if the worker already exists, if not - it creates a new web worker object and runs the code in "script.js":

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

Then we can send and receive messages from the web worker. Add an "onmessage" event listener to the web worker.
w.onmessage = function(event){
  document.getElementById("result").innerHTML = event.data;
}; 

# Tips-7) How to Terminate a Web Worker

When a web worker object is created, it will continue to listen for messages (even after the external script is finished) until it is terminated.

Learn to Terminate a Web Worker

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

index.html
Example: HTML
w.terminate();


# Tips-8) How to Reuse the Web Worker

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

index.html
Example: HTML
w = undefined;


# Tips-9) Full Web Worker Example Code

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

Full Example Web Worker

Follow the Example
index.html
Example: HTML
 <!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> 

Output should be:

Full Example Web Worker

# Tips-10) What is Web Workers and the DOM

Since web workers are in external files, they do not have access to the following JavaScript objects:


Share on: