Web Workers et exécution hors du thread principal
Comprenez comment déléguer les tâches exigeantes en calcul aux Web Workers afin de garder le thread principal libre et réactif.
Web Workers et exécution hors du thread principal est une leçon Web Performance Optimization & Lighthouse gratuite sur CoddyKit. Ceci est la leçon 3 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Web Performance Optimization & Lighthouse, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Web Performance Optimization & Lighthouse comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
Unblocking the Main Thread
When you interact with a website, everything you see and click is handled by the browser's main thread. This thread is like a single lane highway for all your JavaScript code, UI updates, and event handling.
If a heavy task runs on this main thread, it can block everything else, making your website freeze and feel unresponsive. This is where Web Workers come in!
Understanding the Main Thread
The main thread is crucial for a smooth user experience. It's responsible for:
- Parsing HTML and CSS
- Executing JavaScript
- Handling user events (clicks, scrolls)
- Updating the user interface (rendering pixels)
Because JavaScript is single-threaded in the browser, a long-running script on the main thread will pause all these activities, leading to a 'frozen' UI.
Introducing Web Workers
Web Workers allow you to run scripts in the background, in a separate thread, without interfering with the main execution thread of the browser. Think of it as giving your browser an extra lane on the highway for heavy traffic.
- They perform tasks off the main thread.
- They keep the UI responsive during intensive operations.
- They communicate with the main thread by sending messages.
Worker Types: Dedicated & More
There are a few types of Web Workers, but the most common and what we'll focus on are Dedicated Workers.
- Dedicated Workers: Used by a single script. Each instance is tied to one main thread script.
- Shared Workers: Can be accessed by multiple scripts, even from different windows/iframes.
- Service Workers: Used for advanced features like offline experiences, caching, and push notifications (a more specialized type).
Spawning a New Worker
Creating a dedicated Web Worker is straightforward. You instantiate a Worker object, passing the URL of the script that the worker will execute.
This worker script runs in its own isolated global context.
const myWorker = new Worker('myWorker.js');
console.log('Worker created!');Sending Data to a Worker
The main thread communicates with a worker using the postMessage() method. This method sends a message (which can be a string, JSON object, or other data) to the worker.
The data is copied, not shared, between the main thread and the worker.
const myWorker = new Worker('myWorker.js');
myWorker.postMessage({ type: 'startCalculation', data: 1000000 });
console.log('Message sent to worker!');Receiving Worker Messages
To get results or updates from a worker, the main thread listens for the message event on the worker object. The data sent by the worker is available in event.data.
Similarly, the worker script itself listens for messages using self.onmessage.
const myWorker = new Worker('myWorker.js');
myWorker.onmessage = function(event) {
console.log('Result from worker:', event.data);
};
myWorker.postMessage('Start work!');Inside the Worker Script
The script loaded by the worker runs in its own isolated environment. It doesn't have direct access to the DOM or the window object, but it has its own global scope, represented by self.
The worker sends messages back to the main thread using self.postMessage().
// myWorker.js (the worker's script)
self.onmessage = function(event) {
const receivedData = event.data;
console.log('Worker received:', receivedData);
// Perform a task
const result = receivedData + ' processed!';
// Send result back to the main thread
self.postMessage(result);
};Runnable Demo: Heavy Work Offloaded
Here's a demo using a Web Worker to perform a heavy calculation. Observe how the main thread remains responsive (simulated by log messages) while the worker does its job.
First, here's the content for worker.js that performs a sum:
// worker.js
self.onmessage = function(event) {
let sum = 0;
const limit = event.data; // Expecting a number
console.log('Worker: Starting calculation for limit:', limit);
for (let i = 0; i < limit; i++) {
sum += i; // A computationally heavy loop
}
self.postMessage(sum);
console.log('Worker: Calculation finished and result sent.');
};And here's the main script that creates and communicates with it. Try running it!
// This script would run in an HTML page.
// It assumes a 'worker.js' file exists in the same directory.
console.log("Main thread: Starting Web Worker demo.");
try {
// Create a new Web Worker
const myWorker = new Worker('worker.js');
// Listen for messages from the worker
myWorker.onmessage = function(event) {
console.log("Main thread: Received result from worker:", event.data);
console.log("Main thread: UI remains responsive.");
};
// Handle errors from the worker
myWorker.onerror = function(error) {
console.error("Main thread: Worker error:", error);
};
// Send a message to the worker to start a heavy calculation
const calculationLimit = 200000000; // A large number
console.log(`Main thread: Sending calculation request for ${calculationLimit} to worker.`);
myWorker.postMessage(calculationLimit);
// Demonstrate that the main thread is not blocked
let count = 0;
const intervalId = setInterval(() => {
console.log(`Main thread: UI is active... ${count++}`);
if (count > 5) { // Stop after a few messages to keep output short
clearInterval(intervalId);
}
}, 100); // This would represent UI updates
} catch (e) {
console.error("Main thread: Could not create Web Worker. " +
"This environment might not support Web Workers directly or 'worker.js' is missing.", e);
console.log("Main thread: Simulating blocking calculation instead.");
// Fallback for environments without Web Worker support (for CoddyKit's sandbox)
let sum = 0;
const limit = 200000000;
for (let i = 0; i < limit; i++) {
sum += i;
}
console.log("Main thread: Blocking calculation finished. Result:", sum);
console.log("Main thread: UI would have frozen during this calculation.");
}Worker Limitations
While powerful, Web Workers have some limitations due to their isolated nature:
- No DOM Access: Workers cannot directly access or manipulate the Document Object Model (DOM).
- No Window Object: They cannot access the
window,document, orparentobjects. - Local Files: They cannot access local files directly (e.g.,
file://protocol) in all browsers. - Communication: All communication must happen via message passing (
postMessageandonmessage).
Worker Knowledge Check
Let's check your understanding of Web Workers.
Recap: Offloading Tasks
Great job! You've learned how Web Workers can significantly improve your web application's performance and responsiveness.
- Web Workers run scripts in the background, off the main thread.
- They prevent the UI from freezing during heavy computations.
- Communication occurs through message passing (
postMessageandonmessage). - Workers cannot directly access the DOM or
windowobject.
By effectively using Web Workers, you can create smoother, more engaging user experiences.
Questions Fréquemment Posées
La leçon « Web Workers et exécution hors du thread principal » est-elle gratuite ?
Oui — le texte complet de « Web Workers et exécution hors du thread principal » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Web Performance Optimization & Lighthouse, passe à CoddyKit PRO. Le cours Web Performance Optimization & Lighthouse comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Web Workers et exécution hors du thread principal » ?
Comprenez comment déléguer les tâches exigeantes en calcul aux Web Workers afin de garder le thread principal libre et réactif. Tu pratiques Web Performance Optimization & Lighthouse avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Web Performance Optimization & Lighthouse ?
Aucune expérience préalable n'est requise. Web Performance Optimization & Lighthouse sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 3 sur 4.
Combien de temps prend la leçon « Web Workers et exécution hors du thread principal » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Web Performance Optimization & Lighthouse ?
Oui. Chaque leçon Web Performance Optimization & Lighthouse inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Réduire la charge JavaScript
- Stratégies efficaces de chargement des scripts
- Web Workers et exécution hors du thread principal
- Découpage du code et chargement différé