HTML Web Workers API

HTML web workers is the topic of discussion. Essentially, a web worker is JavaScript that executes on the backend without affecting the page’s efficiency.



HTML WebWorkers – What is it?

In HTML pages, when scripts are executed, the page becomes frozen until the script has finished executing.

There is a JavaScript implementation called a web worker that runs silently in the background, independent of other scripts, and does not affect the performance of your web pages. There is no need to stop doing anything you want while the web worker runs in the background, so you can keep clicking, selecting things, etc.


HTML WebWorkers Benefits

HTML Web Workers provide web developers with a powerful tool to execute JavaScript code in a separate thread, freeing up the main thread for other tasks. Here are some of the advantages of using HTML Web Workers:

  • Improved Website Performance: By running background processes in a separate thread, HTML Web Workers improve website performance and responsiveness, reducing the likelihood of website freezing or crashing due to heavy processing.
  • Parallel Processing: HTML Web Workers enable parallel processing, allowing multiple tasks to be executed simultaneously, resulting in faster website experiences for users.
  • Enhanced User Experience: HTML Web Workers help reduce the time it takes to load and process data, resulting in a more seamless and responsive website experience for users.
  • Better Resource Management: HTML Web Workers distribute processing load across multiple threads, reducing the burden on the CPU and memory, resulting in a more efficient use of resources.
  • Compatibility with Legacy Browsers: HTML Web Workers are compatible with most modern browsers and can also be used with older browsers, making the website accessible to a wider range of users.

Browser Compatibility:

The numbers in the table below indicate the first browser version that fully supports the HTML web worker when we talk about HTML webworkers.

API
Web Workers4.010.03.54.011.5

HTML WebWorkers Example:

The following HTML code defines a basic HTML webworkers that performs a counting function in the background:

Example: 

<!DOCTYPE html> <html><body><br><br><br><br><p>Count numbers: <output id="result"></output></p><br><button onclick="startWorker()">Start Worker</button> <br><button onclick="stopWorker()">Stop Worker</button><br><br><p><strong>Note:</strong> Internet Explorer 9 and earlier versions do not support Web Workers.</p><br><br><script><br>var w;<br><br>function startWorker() {<br> if(typeof(Worker) !== "undefined") {<br> if(typeof(w) == "undefined") {<br> w = new Worker("demo_workers.js");<br> }<br> w.onmessage = function(event) {<br> document.getElementById("result").innerHTML = event.data;<br> };<br> } else {<br> document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Workers…";<br> }<br>}<br><br>function stopWorker() { <br> w.terminate();<br> w = undefined;<br>}<br></script><br><br><br> </body></html>

Web Worker File Creation:

Let’s apply external JavaScript to implement our web worker.

The goal here is to write a script that counts. You can find this script in the “demo-workers.js” file:

var i = 0; function timedCount()
{ i = i + 1;

postMessage(i);
setTimeout(“timedCount()”,500);
}

timedCount();

The postMessage() method, which posts a message back to the HTML page, is a key component of the code above.

Important: Web workers are generally implemented for more CPU-intensive tasks rather than for such simple scripts.


Check Web Worker Compatibility:

Ensure the user’s web browser is compatible with web workers before enabling one:

if (typeof(Worker) !== “undefined”) {
// Yes, of course! We support web workers!
// A few lines of code…..
}
else {
// Sorry for the inconvenience! Web Worker support is not available.
}

Web Worker Object Creation:

After obtaining the HTML webworkers file, the next step is to apply it within an Html page.

Here is the code that checks if the worker already occurs, and if not, it makes a new worker object and executes the code in “demo-workers.js”:

if (typeof(w) == “undefined”) { w = new Worker(“demo-workers.js”);
}

Messages can then be sent and received by the web worker.

To the web worker, include an “onmessage” event listener.

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

In response to a web worker posting a message, the event listener is activated. The data collected by the web worker is stored in event.data.


Web Worker Reuse:

You can use the code again by setting the worker variable to undefined once it has been terminated:

w = undefined;

Web Worker Termination:

Even after the external script has completed execution – A web worker object that has been established will continue to listen for messages until it is terminated.

Utilizing the terminate() method will allow you to terminate a web worker, freeing up resources in the browser and computer.

w.terminate();


Example Code of full web worker:

In the.js file, we have already seen the Worker code. Here is the HTML page’s code:

Here is an example of HTML web workers:

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 = "We're sorry! It does not support Web Workers."; } }function stopWorker() { w.terminate(); w = undefined; } </script></body> </html>

Web Workers & the DOM

HTML webworkers don’t have access to these JavaScript objects because they are located in external files:

  • Window object
  • Document object
  • Parent object

Web Workers and the DOM in HTML Overview

Web Workers and the DOM are two crucial elements in web development that can be used together in HTML to achieve several benefits. However, there are also limitations that need to be considered. Here’s a breakdown of the benefits and limitations of using Web Workers and the DOM together in HTML:

Benefits:

  • Separate the UI Thread: By using Web Workers to perform background tasks such as data processing, the UI thread can remain responsive, resulting in a better user experience.
  • Manipulate the DOM: Web Workers can manipulate the DOM, enabling web developers to update website content and structure dynamically. This approach allows web developers to create interactive and responsive web pages.
  • Communication between Threads: Web Workers can communicate with the main thread using messaging protocols, allowing data processing to be performed on a separate thread while displaying results on the UI thread.

Limitations:

  • Cannot Directly Access the DOM: Web Workers cannot directly access the DOM as the DOM is not thread-safe. Therefore, developers must use messaging protocols to communicate between threads and manipulate the DOM accordingly.
  • Complexity: The use of Web Workers and the DOM together can increase the complexity of web development, requiring additional programming and debugging efforts.
  • Limited Browser Compatibility: Web Workers are not supported by some older web browsers, limiting their compatibility with legacy systems.

Do subscribe to our Newsletter below, go get connected with the latest technical information on this site.
We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *