What Is Web Workers API?

Web Workers API allows you to run JavaScript in background threads, separate from the main execution thread. This keeps your UI responsive, improves performance, and enables heavy tasks to run without blocking the user experience.

Web Workers allow the browser to run dedicated JavaScript code in a worker thread separate from the main execution thread. That's useful because it's possible to avoid blocking or at least slowing down the main execution thread when performing computationally expensive, long-running operations.

Almost any JavaScript code can be run in a worker thread. The only limitations are that the DOM can't be manipulated from within the worker thread, and some of the default properties/methods of the global Window object aren't available.

A worker is an object created using a constructor (e.g., Worker()). This object is used to execute a named JavaScript file. The code contained in that file will be executed in a worker thread.

Workers and the main execution thread communicate via a messaging system. Both the worker and the main thread use the postMessage() function for posting messages and the onmessage event for processing incoming messages. Each incoming message body is contained in the data property of an event object.

A worker can spawn new workers, as long as they are hosted on the same origin as the parent page.

Actually, there are different types of web workers:

  • Dedicated workers
  • Shared workers
  • Service workers

Dedicated workers are probably the simplest ones. One dedicated worker can be utilized by only one script.

Shared workers, on the other hand, can be used by multiple scripts running in different browser windows, iFrames, tabs, etc., as long as they are in the same domain as the worker. Communication with shared workers is a bit more complex, as they have to use a shared active port.

Service workers serve as a proxy between the web applications, the browser, and the network (if available). They are intended (among other purposes) for implementing effective offline experiences, intercepting network requests and performing different operations based on whether the network is available, and keeping assets stored on the server synced. Service workers also give access to push notifications and various background sync APIs.

Example Of A Dedicated Web Worker

This example shows how to create and interact with a dedicated web worker. The main.js file contains the main execution code and the worker.js includes code that will be executed in a separate worker thread.

main.js (JavaScript) code snippet
main.jsJavaScript
if (window.Worker) {
	const worker = new Worker("worker.js");
	
	const range = { from: 0, to: 10000 };

	worker.postMessage((range));
	
	console.log("Message is posted from the main thread to the worker!");
	
	worker.onmessage(event => {
		console.log("Message from the worker is received in the main thread:", JSON.stringify(event.data));
	});
} else {
	console.warn("Web Workers aren't supported by this browser.");
}
worker.js (JavaScript) code snippet
worker.jsJavaScript
self.onmessage = (event) => {
	const { data } = event;

	console.log("Worker received a message from the main thread:", JSON.stringify(data));

	const { from, to } = data;
	
	// pretending that some long-running operation is happenning in this thread
	for (let i = from; i <= to; i++) {
		console.log(i);
	}
	
	console.log("Posting a message to the main thread...");
	
	self.postMessage("Result computation completed successfully.");
	
	console.log("Worker posted the message to the main thread!");
}

I hope this article was useful. If you have any questions, don't hesitate to reach out to me via the contacts that can be found on the Contact page!

Related posts

  • JavaScript Memory Management: How to Stop Leaks and Use Less RAM

    JavaScript frees memory for you, but that does not mean you can ignore it. Learn how allocation, garbage collection, and weak references work – and how to write code that stays fast.

  • The 4 Core Challenges of Web System Design

    Every large-scale web application faces the same challenges: handling more users, managing growing amounts of data, maintaining low latency, and ensuring consistency. Learn the architectural patterns used to solve them.

  • What Is Infrastructure as Code (IaC)?

    Infrastructure as Code turns manual infrastructure management into repeatable, version-controlled automation. Explore Terraform, Ansible, Docker, Kubernetes, and the role each plays in modern DevOps.

← Back to blog