Overiew of Web Workers

What are Web Workers?

JavaScript is often described as a single-threaded language. In practice, this refers to the main thread, which is the single thread where the browser does most of the work that you see in the browser. This work includes tasks involved in things such as scripting, some types of rendering work, HTML and CSS parsing, and other kinds of user-facing work that drives the user experience. In truth, browsers do use other threads to do work that you, the developer, don't typically have direct access to—such as GPU threads.

Where JavaScript is concerned, you're generally confined to doing work on the main thread—but only by default. It is possible to register and use additional threads in JavaScript. The feature that allows for multi-threading in JavaScript is known as the Web Workers API.

Web workers are useful when you have computationally expensive work that just can't be run on the main thread without causing long tasks that make the page unresponsive. Such tasks can certainly affect your website's Interaction to Next Paint (INP), so it can be helpful to know when you have work that can be done off of the main thread entirely. Doing so can help create more room for other tasks on the main thread so that user interactions are faster.

There are a few different types of workers in the Web Workers API:

  • Dedicated Workers: These workers are dedicated to a single script. They don't share a global scope with the main thread, but they do have their own global scope.

  • Shared Workers: These workers are shared between multiple scripts. They have a shared global scope with the main thread and other workers.

  • Service Workers: These workers are a special type of worker that act as a proxy between the web page and the network. They can intercept network requests and cache resources to improve performance.

This library focus on dedicated workers, which are the most common type of worker you'll use in web development.