What is web workers?

Web workers are a simple means for web content to run scripts in background threads. The worker thread can perform tasks without interfering with the user interface. You can continue to do whatever you want: clicking, selecting things, etc. while your worker runs in the background.

Why web workers?

Web workers are useful for performing computationally intensive tasks in a background thread. This frees the main browser thread to update the user interface without causing the page to become unresponsive. This is especially important on mobile devices, where a slow or unresponsive script can make the page seem as if it has stopped responding altogether.

What about the browser support?

Web workers are supported in all modern browsers. However, Internet Explorer 10 and below do not support web workers.

How to check browser support?

To check if the browser supports web workers, you can use the following code:

if (window.Worker) {
  // Browser supports web workers
} else {
  // Browser does not support web workers
}

How to create a web worker?

To create a web worker, you need to create a JavaScript file and add the code that you want to run in the background. Then, you need to create a new Worker object and pass the path to the JavaScript file as a parameter.

var worker = new Worker('worker.js');

How to send messages to a web worker?

To send messages to a web worker, you need to use the postMessage() method of the Worker object.

worker.postMessage('Hello World');

How to receive messages from a web worker?

To receive messages from a web worker, you need to use the onmessage event handler of the Worker object.

worker.onmessage = function(event) {
  console.log(event.data);
}

How to terminate a web worker?

To terminate a web worker, you need to use the terminate() method of the Worker object.

worker.terminate();

How to handle errors in a web worker?

To handle errors in a web worker, you need to use the onerror event handler of the Worker object.

worker.onerror = function(error) {
  console.log(error.message);
}

How to pass data to a web worker?

To pass data to a web worker, you need to use the postMessage() method of the Worker object.

worker.postMessage({name: 'John', age: 30});

Conclusion

In this article, we have learned what web workers are and how to use them in JavaScript. We have also learned how to create a web worker, send messages to a web worker, receive messages from a web worker, terminate a web worker, handle errors in a web worker, and pass data to a web worker.


References