Web Workers พร้อมเธรด WASM
ผสาน Web Workers เพื่อเรียกใช้โมดูล WASM ในเธรดแยก ป้องกันการบล็อกส่วนติดต่อผู้ใช้และเพิ่มการตอบสนอง
Web Workers พร้อมเธรด WASM เป็นบทเรียน WebAssembly (WASM) for High Performance Apps ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน WebAssembly (WASM) for High Performance Apps และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส WebAssembly (WASM) for High Performance Apps มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Preventing UI Freezes
Web applications often need to perform complex tasks, like heavy calculations or data processing. If these tasks run directly on the main browser thread, they can cause the user interface (UI) to freeze and become unresponsive.
This leads to a poor user experience. To avoid this, we need ways to run code concurrently, or in parallel, without blocking the UI.
Meet Web Workers
Web Workers are a JavaScript feature that allows scripts to run in the background, separate from the main execution thread of a web page.
- They have their own global scope.
- They cannot directly access the Document Object Model (DOM).
- They communicate with the main thread using messages.
This isolation is key to keeping your UI responsive.
WASM on the Main Thread
By default, when you load and execute a WebAssembly (WASM) module in a web page, it runs on the main JavaScript thread, just like regular JavaScript code.
If your WASM module performs a very long or computationally intensive operation, it will block the main thread. This means the browser won't be able to update the UI, respond to user input, or run other scripts until the WASM task is complete.
WASM + Workers = Power
Combining Web Workers with WebAssembly offers a powerful solution for high-performance web applications. You can:
- Run CPU-intensive WASM computations (like image processing, video encoding, or complex simulations) in a separate thread.
- Keep the main thread free and responsive for UI updates and user interactions.
- Leverage the near-native speed of WASM without sacrificing user experience.
Spawning a Web Worker
You create a Web Worker by instantiating the Worker object with the URL of a script file. This script will then run in its own thread.
The main script can then send messages to this worker, and the worker can send messages back.
const workerCode = `
self.onmessage = (e) => {
console.log('Worker received:', e.data);
self.postMessage('Worker says hello!');
};
`;
const blob = new Blob([workerCode], { type: 'application/javascript' });
const worker = new Worker(URL.createObjectURL(blob));
worker.onmessage = (event) => {
console.log('Main received:', event.data);
};
worker.postMessage('Hello from main!');
console.log('Main thread finished setup.');Loading WASM in a Worker
Loading a WASM module inside a Web Worker is similar to loading it on the main thread. You fetch the .wasm file and instantiate it using WebAssembly.instantiate within the worker's script.
Once instantiated, you can call its exported functions to perform your heavy computations.
// worker.js
self.onmessage = async (e) => {
// Fetch the WASM module
const response = await fetch('my_wasm_module.wasm');
const bytes = await response.arrayBuffer();
// Instantiate the WASM module
const { instance } = await WebAssembly.instantiate(bytes, {});
// Call an exported WASM function
const result = instance.exports.processData(e.data);
// Send result back to the main thread
self.postMessage(result);
};Communicating with Workers
Communication between the main thread and a Web Worker happens via messages using the postMessage() method and the onmessage event handler.
Data passed between threads is copied, not shared, which means complex objects are serialized and deserialized. This ensures thread safety.
const workerCode = `
self.onmessage = (e) => {
console.log('Worker got:', e.data);
self.postMessage('Processing ' + e.data);
};
`;
const blob = new Blob([workerCode], { type: 'application/javascript' });
const worker = new Worker(URL.createObjectURL(blob));
worker.onmessage = (event) => {
console.log('Main got:', event.data);
};
worker.postMessage('a large dataset');
worker.postMessage('another task');
console.log('Main thread sent messages.');Offloading Heavy Calculations
This example demonstrates how to offload a simulated heavy calculation to a Web Worker. The main thread sends a number, the worker performs a Fibonacci-like calculation, and the main thread continues its work without interruption.
Imagine the worker's heavyCalculation function is actually your WASM module's high-performance function.
const workerCode = `
self.onmessage = (e) => {
console.log('Worker: Starting heavy calculation...');
const num = e.data;
let a = 0, b = 1, next;
for (let i = 0; i < num; i++) {
next = a + b;
a = b;
b = next;
}
console.log('Worker: Calculation finished.');
self.postMessage(a);
};
`;
const blob = new Blob([workerCode], { type: 'application/javascript' });
const worker = new Worker(URL.createObjectURL(blob));
worker.onmessage = (event) => {
console.log('Main: Received result:', event.data);
};
worker.postMessage(40); // Send number to worker
console.log('Main: Sent request. UI remains responsive!');
// Simulate other UI work on the main thread
let counter = 0;
const intervalId = setInterval(() => {
console.log('Main: UI update simulation ' + counter++);
if (counter > 3) clearInterval(intervalId);
}, 100);Key Advantages
Using Web Workers with WASM modules brings several significant benefits to your web applications:
- Improved UI Responsiveness: The main thread stays free, preventing freezes.
- Better Performance: Combine WASM's speed with parallel execution.
- Enhanced User Experience: Users experience fluid interactions even during intensive tasks.
- Efficient Resource Utilization: Leverage multi-core CPUs by distributing workload.
Check Your Understanding
Consider a web application that needs to perform complex image filtering. This process takes several seconds to complete.
Which approach would best ensure the user interface remains responsive?
Summary & Next Steps
We've learned how Web Workers provide a separate thread for executing scripts, preventing UI blocking. By loading and running your high-performance WASM modules inside these workers, you can achieve smooth, responsive web applications even with heavy computations.
This combination is powerful for tasks like image processing, data analysis, and complex simulations. In the next lessons, we'll explore more advanced concurrency patterns, including shared memory for even tighter integration.
คำถามที่พบบ่อย
บทเรียน “Web Workers พร้อมเธรด WASM” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “Web Workers พร้อมเธรด WASM” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส WebAssembly (WASM) for High Performance Apps ให้อัปเกรดเป็น CoddyKit PRO คอร์ส WebAssembly (WASM) for High Performance Apps มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “Web Workers พร้อมเธรด WASM”
ผสาน Web Workers เพื่อเรียกใช้โมดูล WASM ในเธรดแยก ป้องกันการบล็อกส่วนติดต่อผู้ใช้และเพิ่มการตอบสนอง คุณปฏิบัติ WebAssembly (WASM) for High Performance Apps ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน WebAssembly (WASM) for High Performance Apps หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน WebAssembly (WASM) for High Performance Apps บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “Web Workers พร้อมเธรด WASM” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน WebAssembly (WASM) for High Performance Apps นี้ได้ไหม
ได้ บทเรียน WebAssembly (WASM) for High Performance Apps ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- Web Workers พร้อมเธรด WASM
- SharedArrayBuffer และอะตอมิกสำหรับ WASM
- การออกแบบแอปพลิเคชัน WASM แบบทำงานพร้อมกัน
- การส่งข้อความและช่องทางระหว่างเธรด WASM