Sobes.tech
Middle

What are web workers and what are they used for?

sobes.tech AI

Answer from AI

Web workers are a way to execute scripts in background threads, separate from the main UI thread.

Their main purposes:

  • Performance improvement: Moving resource-intensive tasks (complex calculations, processing large data volumes, parsing) from the main thread responsible for rendering the interface and handling user events. This prevents page "freezing" and improves application responsiveness.
  • Parallelism: The ability to perform multiple tasks simultaneously, utilizing multi-core processors more efficiently.

There are three types of web workers:

  1. Dedicated Workers: Tied to a specific page and accessible only to it.
  2. Shared Workers: Can be accessed from multiple pages or tabs of the same domain.
  3. Service Workers: Operate as network proxies, intercepting network requests and enabling offline functionality, push notifications, and other features of progressive web apps (PWA).

Principles of operation:

  • Separate context: Workers have their own global object and access to a subset of browser APIs (no access to DOM, window, document, parent).
  • Message exchange: Interaction between the main thread and worker occurs through messages using postMessage() and the onmessage event handler. Data is transferred by value (copied) or by reference (Transferable Objects).

Example of using a Dedicated Worker:

// main.js (main thread)
const worker = new Worker('worker.js'); // Creating a worker

worker.onmessage = (event) => {
  // Handling message from worker
  console.log('Received from worker:', event.data);
};

worker.postMessage('Start complex operation'); // Sending message to worker
// worker.js (worker file)
onmessage = (event) => {
  // Handling message from main thread
  console.log('Received from main thread:', event.data);

  // Performing complex task
  let result = 0;
  for (let i = 0; i < 1000000000; i++) {
    result += i;
  }

  // Sending result back
  postMessage(result);
};