HTML — Web Workers
-
Deconstruct the Request:
- Topic: HTML Course -> Web Workers.
- Previous: Web Storage. Next: SSE (Server-Sent Events).
- Audience: Absolute beginners. Plain language, short sentences, explain terms. Warm tone.
- Format: YAML frontmatter, 150-200 lines, specific headings, multiple code examples, "What the browser displays" blocks, table, blockquote tip/warning, checklist, mini practice.
- Constraint: 100% original content. No copying.
-
Drafting - Section by Section (Mental Outline & Content Generation):
-
Frontmatter:
--- title: Web Workers description: Learn how Web Workers run scripts in the background to keep your webpage fast and responsive. order: 51 --- -
Intro: Needs to connect to Web Storage and introduce the concept.
- Concept: Web Storage saves data. Web Workers do heavy lifting without freezing the page.
- Analogy: Main thread is like a single cashier. Workers are like extra cashiers in the back.
- Drafting: "Welcome back! In the last lesson, we learned how to save data with Web Storage. Now, let's talk about speed and performance. Have you ever clicked a button and watched your browser freeze? That happens when a script takes too long to run. Web Workers solve this problem."
-
What is a Web Worker? (## What is a Web Worker?):
- Explanation: A script that runs in the background. It doesn't touch the screen (DOM).
- Key term: Main Thread. DOM.
- Drafting: "A Web Worker is a JavaScript file that runs separately from your main webpage. Think of your webpage as the main thread. The main thread handles clicks, updates the screen, and runs your primary code. If the main thread gets stuck doing heavy math, the screen stops updating. A Web Worker runs in the background. It can do heavy calculations without blocking the user interface."
-
How to Create a Worker (## How to Create a Web Worker):
- Code Example 1: Simple HTML and JS structure.
- File structure:
index.htmlandworker.js. - Code:
<!DOCTYPE html> <html> <body> <button id="startBtn">Start Worker</button> <script> const myWorker = new Worker('worker.js'); document.getElementById('startBtn').addEventListener('click', () => { myWorker.postMessage('Hello Worker!'); }); </script> </body> </html> - Worker JS:
self.onmessage = function(e) { console.log('Worker received:', e.data); }; - Display: "### What the browser displays: A simple button appears. Clicking it sends a message to the background script. Nothing changes on the screen, but the console shows the message."
-
Communication (## Sending and Receiving Messages):
- Concept: Workers talk via
postMessage. They can't touchdocument. - Code Example 2: Two-way communication.
- HTML:
<input type="number" id="numInput"> <button id="calcBtn">Calculate Square</button> <p id="result"></p> <script> const worker = new Worker('math-worker.js'); document.getElementById('calcBtn').addEventListener('click', () => { const number = document.getElementById('numInput').value; worker.postMessage(number); }); worker.onmessage = function(e) { document.getElementById('result').textContent = 'Result: ' + e.data; }; </script> - Worker JS:
self.onmessage = function(e) { const result = e.data * e.data; self.postMessage(result); }; - Display: "### What the browser displays: You see a number input and a button. When you enter a number and click the button, the result appears below. The calculation happens in the background."
- Concept: Workers talk via
-
Limitations & Table (## Important Limitations):
- Table: Main Thread vs Web Worker.
- Columns: Feature, Main Thread, Web Worker.
- Rows: Access DOM, Access Window, Memory, Performance.
- Drafting Table:
Feature Main Thread Web Worker Update HTML/CSS Yes No Access windowobjectYes No Run heavy calculations Can freeze page Runs safely in background Access Web Storage Yes Yes
-
Blockquote Tip:
- Content: Common mistake about DOM access.
- Drafting: "> Common mistake: Trying to change the HTML inside the worker file. Workers cannot access the DOM. If you write
document.getElementById()insideworker.js, you will get an error. Always send the data back to the main thread to update the screen."
-
Terminating Workers (## Stopping a Web Worker):
- Concept: Workers keep running until stopped. Use
terminate(). - Code Example 3: Stop button.
- Drafting: "Workers stay alive after you create them. This uses memory. You should close them when you are done."
- Code snippet:
myWorker.terminate();
- Concept: Workers keep running until stopped. Use
-
Common Mistakes Checklist (## Common mistakes checklist):
- List:
- Forgetting separate file?
- DOM access in worker?
- Not handling errors?
- CORS issues? (Maybe too advanced? Keep it simple. "Same origin policy" mentioned simply.)
- Drafting:
- Trying to access
documentinside the worker script. - Forgetting to call
terminate()when the worker is no longer needed. - Using the worker for tiny tasks (overhead is too high).
- Forgetting that the worker file must be a separate
.jsfile.
- Trying to access
- List:
-
Mini Practice (## Mini Practice):
- Exercises:
- Create a worker that counts up.
- Send a name, get a greeting back.
- Stop the worker.
- Debug DOM error.
- Drafting:
- Create a worker that listens for a number and sends back the number multiplied by 10.
- Build a page with a "Start" and "Stop" button. Use
terminate()on the stop button. - Write a worker that accesses
localStorage. Does it work? (Yes, workers can access storage). - Try to use
alert()in a worker. What happens? (Error).
- Exercises:
-
Review and Refine (Self-Correction/Simulation):
-
Line Count Check: Let's estimate lines.
- Frontmatter: 4 lines.
- Intro: 5 lines.
- What is: 8 lines.
- Ex 1: 15 lines.
- Display 1: 3 lines.
- Comm: 5 lines.
- Ex 2: 20 lines.
- Worker Ex 2: 5 lines.
- Display 2: 3 lines.
- Table: 8 lines.
- Tip: 4 lines.
- Stopping: 5 lines.
- Checklist: 8 lines.
- Practice: 10 lines.
- Total ~ 93 lines. This is too short. The constraint is 150-200 lines.
-
Expansion Strategy:
- Add more explanation about "Main Thread" vs "Background".
- Add a section on "When to use Web Workers?".
- Expand code examples with comments.
- Add a section on "Shared Workers" vs "Dedicated Workers"? No, keep it beginner. Maybe just mention "Dedicated" is the default.
- Expand the "How it works" flow.
- Add a "Performance" section.
- Make the code examples more robust with comments explaining each line.
- Add a section "Worker Lifecycle".
-
Expanded Drafting:
- Intro: Add more context about the browser engine. "Browsers use a single lane for most tasks..."
- What is: Explain
new Worker(). Explain the file requirement clearly. - Code Ex 1: Add comments inside code blocks.
// This creates the worker instance.// This listens for the click. - New Section:
## When should you use Web Workers?. List scenarios: Image processing, Large data parsing, Complex math. List non-scenarios: Simple DOM updates. - Code Ex 2: Make it a "Counter" example? Or a "Heavy Math" example? A counter is good for showing real-time updates. Let's do a counter that runs in the worker and updates the main thread. This shows continuous communication.
- Code Ex 2 Revised:
<!-- index.html --> <button id="start">Start Counter</button> <button id="stop">Stop Counter</button> <p id="display">0</p> <script> let worker; const display = document.getElementById('display'); document.getElementById('start').onclick = function() { worker = new Worker('counter-worker.js'); worker.postMessage('start'); }; document.getElementById('stop').onclick = function() { if(worker) worker.terminate(); }; // Note: Need a generic worker listener or assign per worker // Better structure for tutorial: </script> - Actually, for beginners, a specific task is better than a counter that needs complex state management. Let's stick to the Calculator but add more text explanation around it. Or add a third example for
terminate. - Let's add
## Cleaning Up Resources. - Code Ex 3: Terminate example.
- Add Comments to all code blocks to increase line count meaningfully.
- Expand the Table: Add a column for "Explanation".
- Expand Practice: Add hints.
- Result: This should push lines to ~160.
-
Refining Text for Tone:
- "Warm but not childish."
- Use "You", "We".
- Avoid jargon without definition.
- "DOM (Document Object Model) is the tree structure of your HTML."
- "Main Thread is the primary line of execution."
-
Final Polish (Mental Representation of Output):
--- title: Web Workers description: Learn how Web Workers run scripts in the background to keep your webpage fast and responsive. order: 51 --- ## Welcome to Web Workers In our last lesson, we explored Web Storage to save data in the browser. Now, let's focus on performance. Have you ever clicked a button and watched your webpage freeze? The screen stops responding, and you cannot scroll or click anything else. This happens when a script performs a heavy task on the main thread. Web Workers solve this problem. A Web Worker is a background script that runs separately from your main webpage. It allows you to run heavy calculations without blocking the user interface. Your page remains smooth and interactive while the worker does the hard work behind the scenes. ## What is the Main Thread? Browsers use a concept called the main thread. The main thread is responsible for updating the screen, handling clicks, and running your primary JavaScript. It is like a single lane on a highway. If a big truck (a heavy task) blocks the lane, all other cars (user interactions) get stuck behind it. A Web Worker acts like an extra lane. It runs in the background. The worker cannot touch the screen directly. It cannot change HTML or CSS. However, it can send messages back to the main thread. The main thread receives the message and updates the screen. This keeps your webpage responsive. ## Creating Your First Worker To use a Web Worker, you need two files. The worker code must live in a separate JavaScript file. You cannot write worker code inside a `<script>` tag in your HTML. Let's create a simple example. We will send a message from the HTML page to a worker file. **File: `index.html`** ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Web Worker Demo</title> </head> <body> <h1>Simple Worker</h1> <button id="sendBtn">Send Message</button> <p id="status">Waiting...</p> <script> // Create a new worker instance pointing to the external file const myWorker = new Worker('worker.js'); // Listen for the button click document.getElementById('sendBtn').addEventListener('click', function() { // Send a string message to the worker myWorker.postMessage('Hello from the main page!'); document.getElementById('status').textContent = 'Message sent!'; }); // Listen for responses from the worker myWorker.onmessage = function(event) { console.log('Worker replied:', event.data); }; </script> </body> </html>File:
worker.js// This code runs in the background // 'self' refers to the worker's context self.onmessage = function(event) { // Receive the data sent from the main page const receivedMessage = event.data; // Log it to the console (visible in DevTools) console.log('Worker received:', receivedMessage); // Send a reply back to the main page self.postMessage('Got your message, boss!'); };What the browser displays
The page shows a button labeled "Send Message" and text saying "Waiting...". When you click the button, the text changes to "Message sent!". Nothing else happens visually, but the worker script runs in the background and processes the message. You can see the logs in the browser's developer console.
Two-Way Communication
Workers communicate using
postMessage. This method sends data from the main thread to the worker, or from the worker back to the main thread. The data is copied, not shared. This ensures safety and prevents conflicts.Here is a practical example. We will calculate the square of a number using a worker. This simulates a heavy task that should not freeze the page.
File:
index.html<!DOCTYPE html> <html lang="en"> <body> <label>Enter a number:</label> <input type="number" id="numberInput" value="1000"> <button id="calcBtn">Calculate Square</button> <p id="result">Result will appear here</p> <script> const worker = new Worker('math-worker.js'); const resultP = document.getElementById('result'); document.getElementById('calcBtn').addEventListener('click', function() { const num = document.getElementById('numberInput').value; resultP.textContent = 'Calculating...'; // Send the number to the worker worker.postMessage(num); }); // Handle the response from the worker worker.onmessage = function(event) { resultP.textContent = 'The square is: ' + event.data; }; </script> </body> </html>File:
math-worker.jsself.onmessage = function(event) { const number = Number(event.data); // Simulate a heavy calculation let result = number * number; // Send the result back self.postMessage(result); };What the browser displays
You see an input box with the number 1000, a button, and a result paragraph. When you click the button, the result text changes to "Calculating...". Almost instantly, it updates to show "The square is: 1000000". The calculation happened in the background, keeping the page smooth.
When to Use Web Workers
Web Workers add complexity to your code. You should only use them when necessary. Use workers for tasks that take a long time to complete. Good examples include processing large images, parsing huge JSON files, or performing complex mathematical formulas.
Do not use workers for simple tasks. Creating a worker has an overhead cost. If a task takes less than a few milliseconds, a worker will actually make your app slower due to the message passing cost.
Important Limitations
Web Workers have specific rules. They run in a sandboxed environment. This means they have restricted access to browser features.
Feature Main Thread Web Worker Access HTML/DOM Yes No Access windowobjectYes No Run heavy calculations Can freeze page Runs safely Access Web Storage Yes Yes Make network requests Yes Yes Use alert()orprompt()Yes No Common mistake: Trying to modify the DOM inside the worker file. Beginners often write
document.getElementById()insideworker.js. This throws an error because workers cannot access the DOM. Always calculate data in the worker, then send the result back to the main thread to update the HTML.Cleaning Up Resources
A Web Worker stays alive after you create it. Even if you finish your task, the worker continues to run in the background. This consumes memory. You should always terminate the worker when you no longer need it.
Use the
terminate()method to stop the worker. This kills the worker thread and releases memory.// Stop the worker and free up memory worker.terminate();You can also check if a worker exists before terminating it to avoid errors.
if (worker) { worker.terminate(); worker = null; }Common mistakes checklist
Review this list to avoid errors when building with Web Workers.
- DOM Access: Did you remove all
documentorwindowreferences from the worker file? - Separate File: Is your worker code in a separate
.jsfile? Inline scripts do not work. - Termination: Did you call
terminate()when the worker is done? - Error Handling: Did you add an
onerrorlistener to catch crashes in the worker? - Data Types: Remember that
postMessagecopies data. You cannot pass complex objects directly without serialization.
Mini Practice
Try these exercises to master Web Workers.
- Create a worker that listens for a name string and sends back a greeting like "Hello, [Name]!". Display the greeting on the HTML page.
- Build a page with a "Start" and "Stop" button. The worker should count up every second and send the count to the page. Use
terminate()to stop the counting. - Write a worker that accesses
localStorage. Read a value and send it back to the main page. Verify that workers can access Web Storage. - Intentionally add
document.write()inside a worker script. Run the code and observe the error message in the console. - Modify the square calculator to handle invalid input. If the user enters text instead of a number, the worker should send back an error message.
Great job! You now understand how to keep your webpages fast using Web Workers. In the next lesson, we will explore Server-Sent Events (SSE) to push updates from the server to your browser.
*Line Count Check:* * The draft looks solid. * Frontmatter: 4 lines. * Sections: Welcome, Main Thread, Creating, Two-Way, When/Limitations, Cleanup, Mistakes, Practice. * Code blocks are substantial. * Table is present. * Blockquote is present. * Checklist and Practice are present. * Tone is warm, explanatory, beginner-friendly. * No copying. Original explanations. * Length estimate: ~160 lines. Perfect. * Output matches constraints. - DOM Access: Did you remove all
-
-
title: Web Workers description: Learn how Web Workers run scripts in the background to keep your webpage fast and responsive. order: 51
Welcome to Web Workers
In our last lesson, we explored Web Storage to save data in the browser. Now, let's focus on performance. Have you ever clicked a button and watched your webpage freeze? The screen stops responding, and you cannot scroll or click anything else. This happens when a script performs a heavy task on the main thread.
Web Workers solve this problem. A Web Worker is a background script that runs separately from your main webpage. It allows you to run heavy calculations without blocking the user interface. Your page remains smooth and interactive while the worker does the hard work behind the scenes.
What is the Main Thread?
Browsers use a concept called the main thread. The main thread is responsible for updating the screen, handling clicks, and running your primary JavaScript. It is like a single lane on a highway. If a big truck (a heavy task) blocks the lane, all other cars (user interactions) get stuck behind it.
A Web Worker acts like an extra lane. It runs in the background. The worker cannot touch the screen directly. It cannot change HTML or CSS. However, it can send messages back to the main thread. The main thread receives the message and updates the screen. This keeps your webpage responsive.
Creating Your First Worker
To use a Web Worker, you need two files. The worker code must live in a separate JavaScript file. You cannot write worker code inside a <script> tag in your HTML.
Let's create a simple example. We will send a message from the HTML page to a worker file.
File: index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Web Worker Demo</title>
</head>
<body>
<h1>Simple Worker</h1>
<button id="sendBtn">Send Message</button>
<p id="status">Waiting...</p>
<script>
// Create a new worker instance pointing to the external file
const myWorker = new Worker('worker.js');
// Listen for the button click
document.getElementById('sendBtn').addEventListener('click', function() {
// Send a string message to the worker
myWorker.postMessage('Hello from the main page!');
document.getElementById('status').textContent = 'Message sent!';
});
// Listen for responses from the worker
myWorker.onmessage = function(event) {
console.log('Worker replied:', event.data);
};
</script>
</body>
</html>
File: worker.js
// This code runs in the background
// 'self' refers to the worker's context
self.onmessage = function(event) {
// Receive the data sent from the main page
const receivedMessage = event.data;
// Log it to the console (visible in DevTools)
console.log('Worker received:', receivedMessage);
// Send a reply back to the main page
self.postMessage('Got your message, boss!');
};
What the browser displays
The page shows a button labeled "Send Message" and text saying "Waiting...". When you click the button, the text changes to "Message sent!". Nothing else happens visually, but the worker script runs in the background and processes the message. You can see the logs in the browser's developer console.
Two-Way Communication
Workers communicate using postMessage. This method sends data from the main thread to the worker, or from the worker back to the main thread. The data is copied, not shared. This ensures safety and prevents conflicts.
Here is a practical example. We will calculate the square of a number using a worker. This simulates a heavy task that should not freeze the page.
File: index.html
<!DOCTYPE html>
<html lang="en">
<body>
<label>Enter a number:</label>
<input type="number" id="numberInput" value="1000">
<button id="calcBtn">Calculate Square</button>
<p id="result">Result will appear here</p>
<script>
const worker = new Worker('math-worker.js');
const resultP = document.getElementById('result');
document.getElementById('calcBtn').addEventListener('click', function() {
const num = document.getElementById('numberInput').value;
resultP.textContent = 'Calculating...';
// Send the number to the worker
worker.postMessage(num);
});
// Handle the response from the worker
worker.onmessage = function(event) {
resultP.textContent = 'The square is: ' + event.data;
};
</script>
</body>
</html>
File: math-worker.js
self.onmessage = function(event) {
const number = Number(event.data);
// Simulate a heavy calculation
let result = number * number;
// Send the result back
self.postMessage(result);
};
What the browser displays
You see an input box with the number 1000, a button, and a result paragraph. When you click the button, the result text changes to "Calculating...". Almost instantly
Related Topics
Frequently Asked Questions about Web Workers
What is Web Workers in HTML?
Web Workers is a fundamental concept in HTML. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Web Workers?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Web Workers.
Why is Web Workers important in HTML?
Web Workers is essential for HTML development. Understanding this concept will help you write better code and solve real-world problems more effectively.