Web Workers improve performance by offloading resource-intensive tasks, allowing the main thread to remain responsive and preventing UI freezes.
Browser
Main Thread
Worker
<html>
<head>
<title>Web Workers Hello World</title>
<script src="main.js"></script>
</head>
</html>
index.html
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
self.onmessage = (msg) => {
console.log('message from main', msg.data);
postMessage('message sent from worker');
};
worker.js
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')
const worker = new SharedWorker('shared-worker.js');
main.js
// 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
// 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