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.
- <!DOCTYPEhtml>
- <scriptrunatscriptrunat="server">
- </script>
- <htmlxmlnshtmlxmlns="http://www.w3.org/1999/xhtml">
- <headrunatheadrunat="server">
- <title></title>
- <script>
- function count()
- {
- var j;
- for (var i = 0; i <= 10000000000; ii = i + 1)
- {
- j += i;
- }
- alert("Value of j is=" + j);
- }
-
- function Hello_Fun()
- {
- alert("Hello World!");
- }
- count();
- </script>
- <style>
- #div1 {
- background-color: blueviolet;
- height: 100px;
- width: 150px;
- margin-left: 50px;
- margin-top: 30px;
- font-size: 24px;
- text-align: center;
- padding-top: 50px
- }
- </style>
- </head>
-
- <body>
- <formidformid="form1" runat="server">
- <div>
- <dividdivid="div1" onclick="Hello_Fun()"><span>Click Me!</span></div>
- </div>
- </form>
- </body>
-
- </html>
- </Script>
When we write the above code of the page in browsers then it will produce the following result.
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.
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.
- 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.
- importScripts("File1.js", "File2.js");
- 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.
-
- var j = 0;
- for (var i = 0; i <= 100000000; i = i + 1)
- {
- j += i;
- }
- 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.
- Obj_.onmessage = function (event) {
- 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.
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”.
- if (window.Worker)
- {
- alert("Web Workers supported by Browser.");
- }
- else
- {
- alert("OOPS! Web Workers not supported by Browser.");
- }
Handling Error
Using “onerror” method we can handle or write the code if any error occur in Web Method.
- worker.onerror = function (event) {
- alert("Oops! An Error is Occur "+event.message);
- };
Let us take a complete code.
- <html>
-
- <head>
- <title></title>
- <script>
- function Hello_Fun()
- {
- document.getElementById("div1").style.backgroundColor = "Red";
- if (window.Worker)
- {
- if (typeof(Obj_) == "undefined")
- {
- var Obj_ = new Worker('Call.js');
- Obj_.onmessage = function(event)
- {
- alert("Your Total Sum is= " + event.data);
- }
- worker.onerror = function(event)
- {
- alert("Oops! An Error is Occur " + event.message);
- }
- Obj_.terminate();
- }
- else
- {
- alert("OOPS! Web Workers not supported by Browser.");
- }
- };
- }
- </script>
- <style>
- #div1 {
- background-color: blueviolet;
- height: 100px;
- width: 150px;
- margin-left: 50px;
- margin-top: 30px;
- font-size: 24px;
- text-align: center;
- padding-top: 50px;
- margin-left: 450px;
- margin-top: 100px;
- }
- </style>
- </head>
-
- <body>
- <formid="form1" runat="server">
- <div>
- <divid="div1" onclick="Hello_Fun()"><span>Click Me!</span></div>
- </div>
- </form>
- </body>
-
- </html>
Design of web page
When we click on div then the following output will be visible.
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
- Web Worker runs JavaScript in the background on a separate thread.
- Web Workers can't call alert() or confirm() functions.
- Web Workers can't access DOM elements from the web page.
- Web Workers can't access global variables from the webpage.
- Web Workers can't access JavaScript functions from the web page.
- Objects such as windows, documents, and parents can't be accessed inside the Web Worker.
- Web Worker comes in two types Dedicated and Shared Web Worker.
- Dedicated web workers come into existence and die along with a web page that created them. It means dedicated Web Worker can’t access across multiple web pages.
- Web Worker object refers to a dedicated Web Worker.
- Shared web workers are shared across multiple web pages.
- Web Worker can use XMLHttp request to communicate with the server.
Summary
In this article, we learned about HTML5 - Web Workers.
Thanks for reading the article.