Web Workers 

Web Workers are a JavaScript API that enables running scripts in the background without blocking the main thread.

What 

Web Workers improve performance by offloading resource-intensive tasks, allowing the main thread to remain responsive and preventing UI freezes.

Why 

How 

  • Create a new Worker object
  • Specify the script file to run in the background
  • Communicate with the worker using messages

Since 

3 April

2009

Support 

Since 

Internet Explorer 10

Firefox 3.5

Chrome 4

Safari 4

How 

Why 

Browser

Main Thread

Worker

TBT

Total Blocking Time

Why 

FID

First Input Delay

Why 

INP

Interaction to Next Paint

Why 

How 

<html>
  <head>
    <title>Web Workers Hello World</title>
    <script src="main.js"></script>
  </head>
</html>

index.html

How 

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

worker.onmessage = (msg) => {
  console.log('message received from worker', msg.data);
};

worker.postMessage('message sent to worker');

main.js

How 

self.onmessage = (msg) => {
  console.log('message from main', msg.data);

  postMessage('message sent from worker');
};

worker.js

Types 

Dedicated Worker

Shared Worker

Exclusive execution context

A Dedicated Worker is associated with a single JavaScript script and has its own isolated execution context.

Use

Dedicated Workers are useful when you have a specific task that should not share data or resources with other Workers, and only one script needs to access them.

Shared execution context

A Shared Worker can be shared among multiple scripts in different browser windows or tabs. 

Use

Are useful when you want to share data or resources between multiple script instances in different browsing contexts, such as in a multi-user web application or in an application that uses multiple browser tabs or windows.

new Worker('worker.js')
new SharedWorker('worker.js')

How 

const worker = new SharedWorker('shared-worker.js');

main.js

Shared Worker

What 

Dedicated Worker

  • Image and video processing
  • Scientific and mathematical calculations
  • File uploading and processing
  • Geolocation and mapping
  • Online games
  • Artificial intelligence and machine learning on the web
  • Real-time data analysis and processing
  • Encryption and security

What 

Shared Worker

  • Real-time collaborative applications
  • Push notifications
  • Session management and authentication
  • Shared caching
  • Multiplayer online games
  • Data analysis and event tracking
  • Communication between windows or tabs
  • Real-time user interface updates

Code 

Dedicated Worker

// Create a Dedicated Worker
const worker = new Worker('worker.js');

// Define a function to handle Worker messages
worker.onmessage = function (e) {
  console.log('Processed data:', e.data);
};

// Send a network request to the Worker
const apiUrl = 'https://api.example.com/data';
worker.postMessage({ type: 'fetch', url: apiUrl });

  Process Data in a Worker

main.js

Code 

Dedicated Worker

// Handle main thread messages
self.onmessage = function (e) {
  const message = e.data;

  if (message.type === 'fetch') {
    // Make a network request
    fetch(message.url)
      .then((response) => response.json())
      .then((data) => {
        // Perform data processing
        const processedData = processData(data);

        // Send processed data back to main thread
        self.postMessage(processedData);
      })
      .catch((error) => {
        console.error('Error al obtener datos:', error);
      });
  }
};

// Function to process data (just as an example)
function processData(data) {
  // Here you can perform any necessary processing
  // on the data.
  // For example, filtering, transforming or adding
  // additional information.

  // Return processed data
  return { processed: true, data };
}

  Process Data in a Worker

worker.js

Don't 

Access to...

  • DOM (Document Object Model)
  • Global Variables of the Main Thread
  • Objects Related to the Browser Environment
  • Direct Interaction with User Events
  • Browser History Manipulation
  • Access to Most Web Platform APIs
  • Direct Access to Local or External Resources

Web Workers

By Joan León

Web Workers

  • 404