HTML5 introduced the web worker concept a long time ago. In this article, we will see the use of web workers in real scenarios.
In a nutshell, a web worker is a JavaScript code that runs in the background (without refreshing the page) and without adding any performance overhead on the page. So that means, you can continue using your site by clicking here and there while web worker is doing its assigned functionality in the background.
Web worker runs independently of other scripts, so plumbing of code is relatively easy. It does support most of the common browsers today; i.e., Google Chrome, Internet Explorer (10 onwards), Firefox, etc.
Is Web Worker Supported for my development work?
Before we really go into developing the web worker, let us do a small check to see if it is supported in our development scenarios.
The below simple code should help you.
- if (typeof(Worker) !== "undefined") {
- alert(“Yes, Web worker is supported”);
- } else {
- alert(“No, Web worker is not supported”);
- }
After running the above script, if the answer is "Yes" … We are good to go ahead with a web worker.
Basic syntaxes to get started
Create a Web Worker Object,
- var worker = new Worker(“worker.js”);
Send messages using a web worker
To send the message from a web worker, we need to add “onmessage” event listener to our worker role.
- w.onmessage = function(event) {
- document.getElementById("result").innerHTML = event.data;
- };
Terminate Web Worker
Once we are finished with the role of web worker, we should release the browser resources
Reuse Web Worker
We can reuse the same web worker to carry out different dynamic functionalities.
Once we set our web worker variable to undefined, we can reuse it for different purposes.
Web Worker Implementation Scenarios
I have seen others developing the Web workers effectively using the below implementation approaches:
- Web Worker File
- Inline code
We can pass complex types in/out of Workers such as File, Blob, ArrayBuffer, and JSON objects.
Web Worker File
As we discussed earlier, the Web worker runs independently of other scripts. We can create an independent js file that will be designated to work as a worker.
Let’s take a simple example of a timer.
- Create a JS file named, timer.js
- Inside the file, add below code which ticks the time by incrementing the count by 1.
- var time = 0;
-
- function timer() {
- time = time + 1;
- postMessage(i);
- setTimeout("timer()", 100);
- }
- timer();
- In our page, use the above timer.js to perform web worker
- if (typeof(Worker) == "undefined") {
- var w = new Worker("timer.js");
- }
Inline code
We can also have the inline code for web worker processing.
- Instead of a file, create a function for a web worker.
- function webRoleFunction() {
- setInterval(function() {
- time = time + 1;
- postMessage(i);
- }, 100);
- }
- Now, we will have to convert above function to string equivalent
- var code = webRoleFunction.toString();
- code = code.substring(code.indexOf("{") + 1, code.lastIndexOf("}"));
- We will create a BLOB to store this code
- var blob = new Blob([code], { type: "application/javascript" });
- var blobURL = window.URL.createObjectURL(blob);
- var w = new Worker(blobURL);
Blob URLs are unique and last for the lifetime of your application. We should explicitly release the created BLOBs by
- window.URL.revokeObjectURL(blobURL);
Loading External Scripts
Web worker runs in its own thread. That means you will have to load the external scripts by providing the absolute URLs only. Note, relative URLs will not work to load external files.
importScripts() function can be used to load external files.
- w.onmessage = function (e) {
- var data = e.data;
-
- if (data.url) {
- var url = data.url.href;
- var index = url.indexOf('index.html');
- if (index != -1){
- url = url.substring(0, index);
- }
- importScripts(url + 'externalScript.js');
- }
- }
Error Handling
We should have a JavaScript logic to handle the errors raised by web worker.
- var worker = new Worker('workerWithError.js');
- worker.addEventListener('message', onMsg, false);
- worker.addEventListener('error', onError, false);
- worker.postMessage();
In this article, we studied HTML 5 Web Workers.