Posted January 25Jan 25 You are reading Part 28 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 5]IntroductionJavaScript is single-threaded by default, meaning it executes code sequentially in a single thread. However, for CPU-intensive tasks, Web Workers allow JavaScript to run code in parallel threads, improving performance and responsiveness.1. Understanding Web WorkersWeb Workers enable JavaScript to run scripts in the background, separate from the main thread, preventing UI freezes.Types of Web Workers:Dedicated Workers – Each worker has its own script and is used by a single script.Shared Workers – Can be accessed by multiple scripts across different browser contexts (e.g., iframes, tabs).Service Workers – Used for caching, push notifications, and background sync.2. Creating a Web WorkerA Dedicated Web Worker is created using the Worker constructor.Step 1: Create a Worker Script (worker.js)self.onmessage = function(event) { let result = event.data * 2; // Process data self.postMessage(result); // Send data back }; Step 2: Initialize the Worker in the Main Threadlet worker = new Worker("worker.js"); worker.postMessage(10); // Send data to worker worker.onmessage = function(event) { console.log("Received from worker:", event.data); }; 3. Web Workers vs Main Thread ExecutionUsing Web Workers prevents blocking the UI thread. For example:Without Web Workers (Blocking UI Thread)function compute() { let sum = 0; for (let i = 0; i < 1e9; i++) { sum += i; } console.log("Computation Done:", sum); } compute(); // UI will freeze during execution With Web Workers (Non-Blocking Execution)let worker = new Worker("worker.js"); worker.postMessage("start"); // Moves computation to a separate thread 4. Communication Between Main Thread and Web WorkersWeb Workers use the postMessage API for communication.Sending Data to a Workerworker.postMessage({ task: "calculate", value: 50 }); Receiving Data from a Workerworker.onmessage = function(event) { console.log("Result from worker:", event.data); }; 5. Terminating a Web WorkerTo stop a worker manually, use worker.terminate().worker.terminate(); Inside the worker, it can self-terminate using:self.close(); 6. Shared Workers (Multiple Scripts Using the Same Worker)Shared Workers allow multiple browser contexts (e.g., different tabs) to communicate with a single worker.Creating a Shared Worker (shared-worker.js)self.onconnect = function(event) { let port = event.ports[0]; port.onmessage = function(e) { port.postMessage("Received: " + e.data); }; }; Connecting to a Shared Workerlet sharedWorker = new SharedWorker("shared-worker.js"); sharedWorker.port.postMessage("Hello Worker"); sharedWorker.port.onmessage = function(event) { console.log(event.data); }; 7. Service Workers (For Background Sync & Caching)Service Workers run separately from the web page and enable caching, push notifications, and offline functionality.Registering a Service Workerif ('serviceWorker' in navigator) { navigator.serviceWorker.register("service-worker.js") .then(reg => console.log("Service Worker Registered")) .catch(err => console.error("Service Worker Failed:", err)); } 8. When to Use Web Workers?Use CaseBest ChoiceHeavy computations (e.g., large loops, encryption)Dedicated WorkerSharing data across multiple tabsShared WorkerBackground caching & push notificationsService WorkerYou are reading Part 28 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 5]
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.