Introduction

JavaScript work on a single thread environment, it means we can’t run multiple scripts at the same time. JavaScript will hang your browser in a situation where CPU utilization is high. A web worker is a JavaScript running in the background, without affecting the performance of the page.
Firstly, we will understand why we need web workers. Let us take an example.
  1. <!DOCTYPEhtml>
  2. <scriptrunatscriptrunat="server">
  3. </script>
  4. <htmlxmlnshtmlxmlns="http://www.w3.org/1999/xhtml">
  5. <headrunatheadrunat="server">
  6. <title></title>
  7. <script>
  8. function count()
  9. {
  10. var j;
  11. for (var i = 0; i <= 10000000000; ii = i + 1)
  12. {
  13. j += i;
  14. }
  15. alert("Value of j is=" + j);
  16. }
  17. function Hello_Fun()
  18. {
  19. alert("Hello World!");
  20. }
  21. count();
  22. </script>
  23. <style>
  24. #div1 {
  25. background-color: blueviolet;
  26. height: 100px;
  27. width: 150px;
  28. margin-left: 50px;
  29. margin-top: 30px;
  30. font-size: 24px;
  31. text-align: center;
  32. padding-top: 50px
  33. }
  34. </style>
  35. </head>
  36. <body>
  37. <formidformid="form1" runat="server">
  38. <div>
  39. <dividdivid="div1" onclick="Hello_Fun()"><span>Click Me!</span></div>
  40. </div>
  41. </form>
  42. </body>
  43. </html>
  44. </Script>
When we write the above code of the page in browsers then it will produce the following result.
warning

Why this warning occur?

As we know that JavaScript is a single thread process. In the above code, we call a function (count) that makes a large calculation and due to this calculation web browser becomes unresponsive because JavaScript has a single thread and this thread is occupied by the “count” method.

How to resolve this issue?

There are several methods likes setTimeout(), setInterval(), and xmlHTTPRequest that provide asynchronous execution of code. Asynchronous events are processed after the currently executing script yielded. The good news is that HTML5 gives us something better than these approaches. Now read about Web Worker.

Introduction to Web Worker

The Web Workers define an API to run a background script in web application. Web Workers do all the computationally expensive tasks without interrupting the user interface and typically run on separate threads. In other words, Web Workers run specific code on a separate thread from general JavaScript thread. Web Workers allow running long-running scripts that are not interrupted by scripts that respond to clicks or other user interactions.

Why Web Workers doesn’t block Browser UI?

The reason is that Web Workers can’t access the web page window object using the “window. the document” which means the Web Workers doesn’t have direct access to a component of web pages such that Web Workers can’t interrupt the browser UI.

Browser Support

The following list shows the version of the first browser that supports Web Workers.
browser

How Did Web Workers work?

Initialize the URL of JavaScript file
Using the Worker constructor we define the URL of JavaScript file that contains the code for our program. In the constructor, we pass the path as a parameter. The following code shows a demo.
  1. var Obj_ = new Worker('Call.js');
If the application has more than one JavaScript file then we can use importScript() method in which we can pass multiple paths of file separated by a comma.
  1. importScripts("File1.js", "File2.js");
  1. If any specified file doesn’t exist or workers return 404, the worker will stop to work. If the file exists then Web Worker will spawn a new worker thread, which is downloaded asynchronously.
Paste the following code in the “Call.js” file.
  1. //JavaScript File Code
  2. var j = 0;
  3. for (var i = 0; i <= 100000000; i = i + 1)
  4. {
  5. j += i;
  6. }
  7. postMessage(j);
Send Data from Web Worker to its parent page:
In the above code, we use the postMessage() method. Once the connection link is stabilized then all communication b/w Web Browser and its parent page is performed by postMessage() method. This method only accepts a single argument.

Received Data at Parent Page

At parent page message/data is received by “onmessage” event. Depending on browser or browser version, postMessage() can accept either a string or JSON object as its single argument. The latest versions of the modern browsers support passing a JSON object.
  1. Obj_.onmessage = function (event) {
  2. alert("Your Total Sum is= " + event.data);
Using data property of event object we can access the message or data attached to the event.

Terminate the Web Worker Object

Once the Web Browser object is created then it is necessary to terminate it because it will continue to listen for messages even after the external script is finished until it is terminated. To terminate the object using the “terminate ” method.
  1. Obj_.terminate();

Checking Browser Support

To check whether the current browser supports the Web Worker or not we can use “window.Worker” property. This property return “true” if browser support Web Worker else returns “false”.
  1. if (window.Worker)
  2. {
  3. alert("Web Workers supported by Browser.");
  4. }
  5. else
  6. {
  7. alert("OOPS! Web Workers not supported by Browser.");
  8. }

Handling Error

Using “onerror” method we can handle or write the code if any error occur in Web Method.
  1. worker.onerror = function (event) {
  2. alert("Oops! An Error is Occur "+event.message);
  3. };
Let us take a complete code.
  1. <html>
  2. <head>
  3. <title></title>
  4. <script>
  5. function Hello_Fun()
  6. {
  7. document.getElementById("div1").style.backgroundColor = "Red";
  8. if (window.Worker)
  9. {
  10. if (typeof(Obj_) == "undefined")
  11. {
  12. var Obj_ = new Worker('Call.js');
  13. Obj_.onmessage = function(event)
  14. {
  15. alert("Your Total Sum is= " + event.data);
  16. }
  17. worker.onerror = function(event)
  18. {
  19. alert("Oops! An Error is Occur " + event.message);
  20. }
  21. Obj_.terminate();
  22. }
  23. else
  24. {
  25. alert("OOPS! Web Workers not supported by Browser.");
  26. }
  27. };
  28. }
  29. </script>
  30. <style>
  31. #div1 {
  32. background-color: blueviolet;
  33. height: 100px;
  34. width: 150px;
  35. margin-left: 50px;
  36. margin-top: 30px;
  37. font-size: 24px;
  38. text-align: center;
  39. padding-top: 50px;
  40. margin-left: 450px;
  41. margin-top: 100px;
  42. }
  43. </style>
  44. </head>
  45. <body>
  46. <formid="form1" runat="server">
  47. <div>
  48. <divid="div1" onclick="Hello_Fun()"><span>Click Me!</span></div>
  49. </div>
  50. </form>
  51. </body>
  52. </html>
Design of web page
Click me
When we click on div then the following output will be visible.
run
The above example shows that when we click on div at that time background color of div will change and we also get output from JavaScript code. This shows that JavaScript of the “Call.js” file runs on a separate file and this JavaScript code doesn’t conflict with JavaScript of the web application.
Point to Considered

Summary

In this article, we learned about HTML5 - Web Workers.
Thanks for reading the article.