WEB WORKERS

A WEB WORKER SCRIPT JAVASCRIPT is running without affecting the performance of the page.

Before when running a JavaScript script, the site did not respond until the script was finished. Now with WEB WORKER in the SCRIPT JAVASCRIPT runs in the background, without affecting the website, with which we can continue working normally.

Syntax for creating an object WORKER WEB

wk=new Worker("worker.js");

Creates the "wk" which is a WEB WORKER running code "worker.js"

Example of using WEB WORKER:

A. - Create the JavaScript file with the code WEB WORKER

For example we can create the file "worker.js"

var i=0; function count() {   i=i+1;   postMessage(i);   setTimeout("count()",1000); } count();

Explanation of the file "worker.js"

There is the "count" every 1000 milliseconds is increasing by 1 the value of the variable "i".

By the "postMessage" is sent back to the website the value of the variable "i".

2 - Create an object WORKER WEB on our website "worker.htm"

We have the following website "worker.htm"

<!DOCTYPE html> <html> <body> <p>Count: <output id="count"></output></p> <button onclick="startMyWorker()">Start My Worker</button> <button onclick="stopMyWorker()">Stop My Worker</button> <script> var wk; function startMyWorker() {   if(typeof(Worker)!=="undefined")   {     wk=new Worker("worker.js");     wk.onmessage = function (event)     {        document.getElementById("count").innerHTML=event.data;     };   }   else   {      document.getElementById("count").innerHTML="Sorry, your browser does not support Web Worker";   } } function stopMyWorker() {   wk.terminate(); } </script> </body> </html>

Explanation of the previous file:

Inside the html file, there is the JavaScript code to handle the WEB WORKER.

To verify that your browser supports WEB WORKER:

if(typeof(Worker)!=="undefined")

To create the object JAVASCRIPT WEB WORKER

wk=new Worker("worker.js");

To retrieve the values that is taking our WEB WORKER "wk" and to show them in our website "worker.htm" in the "count":

wk.onmessage = function (event) {   document.getElementById("count").innerHTML=event.data; };

To terminate the execution of our WEB WORKER "wk"

wk.terminate();