HTML Web Workers
Long JavaScript loops can freeze buttons and scrolling. Web Workers move heavy work to a background thread.
Direct answer
Create new Worker("worker.js"), then postMessage data to the worker and listen for message events back. Workers cannot touch the DOM directly — they compute and return results. Serve files over http(s) for reliable worker loading.
Worker pattern (page side)
html<script>
const w = new Worker("worker.js");
w.postMessage(40);
w.onmessage = (e) => console.log("result", e.data);
</script>
worker.js would listen for onmessage, compute, and postMessage a result. Exact worker file contents are a JavaScript topic — here you learn why HTML pages use them.
Try it
- Read an introductory worker example from a trusted docs site
- Note that DOM updates stay on the main page script
- Think of one heavy task (large JSON filter) that could move to a worker
- Remember this is optional advanced material
Easy mistakes
- Expecting workers to call
document.querySelectordirectly - Loading workers from incompatible origins or odd file paths
- Using workers for tiny tasks that do not need them
Summary
- Workers run JS off the UI thread
- Communicate with messages
- No direct DOM access from workers
- Use for heavy computation
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top