For enquiries call:

Phone

+1-469-442-0620

April flash sale-mobile

HomeBlogWeb DevelopmentWeb Workers in JavaScript [A Complete Guide]

Web Workers in JavaScript [A Complete Guide]

Published
29th Jan, 2024
Views
view count loader
Read it in
12 Mins
In this article
    Web Workers in JavaScript [A Complete Guide]

    JavaScript was created and designed for running small bits of scripts within the web browser. It was praised and highly adopted due to the simplicity and straightforwardness of the language, and no one expected it to do heavy computational and CPU-intensive tasks at the time. It was a language loved by amateur programmers starting to get their head into the “Logic Building” world of programming. Fast Forward 20 years, JavaScript is running the whole web app business of the modern world. From DOM Manipulation at the front end to managing whole servers and backend, all of the tasks can be (and usually are) done by JavaScript. 

    What are Web Workers in JavaScript?

    JavaScript Web Workers allows web content to run in the background without interfering with the user interface. JavaScript is a single-threaded language, so all the script execution is done by one single thread called the Main thread. The main thread usually does all the heavy lifting; this can cause trouble when you try to execute a process when the main thread is already engaged in executing some other CPU-intensive process. This is where Web Workers in HTML5 come into play. Using web workers, you can transfer some processes from the Main thread to the Worker thread. This will free up the main thread for other tasks while the worker thread does the CPU-intensive tasks. Learn about multi-threading in Full Stack Java course. 

    Browser Support

    Most modern browsers, such as Chrome, Firefox, Safari, and Edge, support web workers in JavaScript. This support enables me, the developer, to take advantage of parallel processing and execute the background scripts separately from the main thread.

    Support of WebWorker API
    Benestudio

    Web workers in JavaScript help offload complex tasks from the developer and help improve the responsiveness and smoothness of web applications in the user interface. However, I must still be extra cautious when searching for web worker support that is valid for specific browser versions.

    Real-World Example: Web Workers in JavaScript

    Web workers in JavaScript make web applications run faster in the real world. Imagine, for instance, an operation requiring heavy computations or handling massive amounts of data, but the end user interface should not become unresponsive.

    Web Workers in JavaScript
    auth0

    Let’s see how web workers work in JavaScript. Web workers allow developers to delegate these intensive tasks to a different thread, leaving the main thread accessible to user activities. For example, web workers in JavaScript can handle complex rendering algorithms for charts and graphs in a data visualization application. This keeps the user interface from freezing during these computations, leading to a more fluid and better user experience.

    Thus, web workers facilitate developers to create highly optimized and friendly web applications that smartly delegate the processing jobs across multiple concurrent threads.

    Web Workers - Common Use Cases

    HTML Web Workers usually do offload tasks. They are used to offload the main thread so that it can be used for other tasks that need immediate action. 

    • It can be used to perform some CPU-intensive work. 
    • It is also used for polling URLs in the background. 
    • In online code editors, it's used in syntax highlighting. 

    In short, we can use HTML Web Workers when we want to perform some task and don't want the user interface to remain stuck until that task gets executed. 

    Web Workers Communication

    To offload(transfer) the task from the main thread to the worker thread and then again transfer the result back from the worker thread to the main thread, we need some sort of communication channel between these two threads, or we can say scripts. 

    We can set up this communication channel between the main script and the worker script in two ways: 

    1. postMessage(Method 

    In this method, we create a separate worker script and connect it with the main script.js file using the .postMessage() and .onmessage() event listener. We also create an object of the Worker class using its constructor, and we define the path of the worker script in it. 

    const worker = new Worker(worker.js);  
    Sending and Receiving a message from the main script to the worker script: 
    // main.js 
    btn1.addEventListner('click', (event)=>{ 
    worker.postMessage('Hello Worker'); // Using the postMessage to send Message from the main.js to worker.js 
    }); 
    worker.onmessage = function(message) 
    alert(`The sum is: ${message.data}`); 

    Receiving and Sending the message from the main script to the worker script: 

    //worker.js 
    self.onmessage = function(message){ // Using onmessage to receive the message in the worker.js 
    let sum=0; 
    for(let i=0; i<10000000; i++) 
    sum += i; 
    self.postMessage(sum); // Using postMessage to send the answer back to the main.js 
    } 

    2. Broadcast Channel

    Broadcast Channel, also known as the Broadcast Channel API, allows basic communication between browsing contexts (like windows, frames, tabs, or iframes). To communicate with the worker, we create a BroadcastChannel object. The frames or workers we want to communicate with don't need to be kept in our reference list because they can all "subscribe" to a channel by creating their BroadcastChannels with the same name and have bi-directional communication between all of them. 

    A) Creating Broadcast Channel: 

    const bc = new BroadcastChannel('newChannel'); 

    b) Sending A Message: 

    bc.postMessage('Message is sent through a broadcast channel'); 

    c) Receiving A Message: 

    bc.onmessage = (event)=>{ console.log(event);} 

    d) Disconnecting A Channel: 

    bc.close(); 

    Web Workers API 

    A worker is an object of the Worker class created using a constructor where we have to mention the path of the worker script. The worker script contains the code that will run in the worker thread. Web Workers are of two types: 

    1. Dedicated Workers

    The workers that are utilized by a single script with context represented by a DedicatedWorkerGlobalScope object are Dedicated Workers. Dedicated workers are only accessible by the script that calls it.  

    const worker = new Worker('worker.js'); 

    This creates a dedicated web worker. 

    2. Shared Workers

    The workers that can be used by multiple scripts running as long as they are in the same domain as the worker and different windows, IFrames, etc., are known as Shared Workers. Shared workers are more complicated than dedicated workers because, in shared workers, scripts must communicate via an active port.  

    const worker = new SharedWorker('worker.js'); 

    This creates a shared web worker. 

    How Do Web Workers Work in JavaScript? 

    A) Prerequisites 

    To learn how web workers work in the JavaScript framework, you should know the following concepts: 

    • Basics of JavaScript 
    • Event listeners 
    • Callback functions 
    • Web Worker API 

    Learn the basics of web workers' JavaScript performance and more about in online Web Development course. 

    B) Integrating Web Worker with JavaScript 

    When we want to offload some CPU-intensive task from the main thread to a background thread that can function independently so that the main thread can work on other important tasks without any user interface glitches, for this purpose, we use web workers. 

    To integrate web workers in our single-threaded JavaScript code, we first need to create an object of the Worker class using its constructor. Before even doing this, we need to create a separate script for our worker thread. This script will contain the code we want to execute on the worker thread. We can name this anything, but I like to call it worker.js script. 

    We need to specify the name of the worker script in the constructor. This is how the main script and worker script set up a connection between them. Now, write your main script as you would. Just in place of the CPU-intensive task that you want to offload to the worker thread, you have to write a worker.postMessage() function. This function will make a POST API request to the worker script that we created above. And whatever task we mentioned in the worker.js file will start executing. Now the worker.js file will run independently without interfering with the main script file. 

    When the worker.js file completes the execution, it can post its result using the same .postMessage(result) method. However, this time the file itself will call the postMessage function. Hence we'll use self.postMessage(result). 

    To receive the worker.js message, use the worker.onmessage event listener in the main script file. 

    Let’s see a web worker example. 

    Output: Without Web Workers 

    C) Implementing Web Worker 

    Let's take an example where we have a webpage with two buttons in it. One button is the "Run calculate function" and another is the "Change the background" button. We just have these two things on the webpage. The "Run calculate function" button will trigger the calculate function that'll calculate the sum of the first billion numbers. The "Change the background" button will trigger the function that'll change the background color of the webpage.  

    We can say that calculating the sum of the first billion numbers is a CPU-intensive task. If we try to perform both actions in the same thread, the change background() function will not run until the calculate() function has finished executing. We can't do anything on the webpage until the calculate() function finish executing, and this makes our webpage slow and choppy.  

    To improve this situation, we can use a separate worker.js script and offload the CPU-intensive task to that. Let's see the javascript web worker example.  

    //main.js 
    const worker = new Worker(worker.js) // creating a new instance of the Worker class. 
    // And also defining the path of the worker script where the code that needs to be offloaded will be kept. This script is called a worker script  
    const sumBtn = document.querySelector("#sumBtn"); 
    const bgBtn = document.querySelector("#bgBtn"); 
    sumBtn.addEventListner('click', (event) => { 
    worker.postMessage('Hello Worker');  // We use postMessage to talk between main script (thread) and worker script (thread). 
    });  
    worker.onmessage = function(message){ 
    alert(`The final sum is ${message.data}`); 
    } // Receiving the message from the worker.js script 
    bgBtn.addEventListener('click', (event)=>{ 
    if(document.body.style.background !== "blue") 
    document.body.style.background = "blue"; 
    else 
    document.body.style.background = "green"; 
    }); 
    //worker.js 
    self.onmessage = function(message){ 
    let sum = 0; 
    for(let i=0; i<10000000000; i++) 
    sum += i;  
    self.postMessage(sum); 
    // This'll return the sum back to the main thread 
    } 

    Output: With Web Workers 

    Service Worker vs Web Worker

    FeatureService WorkerWeb Worker
    ContextRuns in the background of a web page or app and is associated with the entire domain.Runs in the background of a web page and is dedicated to specific tasks within that page.
    Use CasePrimarily used for caching, push notifications, background sync, and network interception.Primarily used for parallelizing tasks to improve performance, such as heavy calculations or data processing.
    Access to DOMCannot directly access the DOM.Cannot directly access the DOM.
    CommunicationCommunicates with the main thread using postMessage and events.Communicates with the main thread using postMessage and events.
    LifecycleIt has its own lifecycle independent of the web page.Tied to the lifecycle of the web page.
    ScopeIt has a broader scope, affecting multiple pages or the entire application.It has a limited scope, typically associated with a single web page.
    Browser SupportSupported in modern browsers.Supported in modern browsers.
    Main Use CaseEnables features like offline support, background synchronization, and push notifications.Used for parallelizing tasks to improve performance, especially in computationally intensive applications.
    File LocationUsually registered from a separate JavaScript file.Created and instantiated directly in the main JavaScript file.

    When Should You Use JavaScript Web Workers?

    Web workers can be anywhere we need multi-thread execution functionality, like in the case of: 

    • Dashboard pages where real-time data is displayed 
    • To show stock prices, real-time active users(like in Hotstar when watching a game) 
    • Syntax highlighting in online code editors. 
    • Fetching huge files from the server 
    • Autosave functionality 
    • Spell check functionality 

    Looking to master Python? Discover the best course for learning Python and unlock endless possibilities. Start coding like a pro today!

    How to Create and Use Web Workers in JavaScript? 

    Creating and using Web Workers in JavaScript involves several steps to leverage the benefits of parallel processing for improved application performance. Below, I have placed one from many Javascript web worker methods for reference:

    Step 1: Create a Web Worker File

    I will create a separate JavaScript file for my Web Worker. Let's name it worker.js.

    // worker.js
    onmessage = function (e) {
      // Handle data received from the main thread
      const result = processData(e.data);
      // Send the result back to the main thread
      postMessage(result);
    };
    function processData(data) {
      // Perform my heavy computations or data processing here
      // ...
      return processedData;
    }

    Step 2: Instantiate Web Worker in the Main Script

    In my main JavaScript file (e.g., main.js), I’ll create a new Web Worker using the Worker constructor.

    // main.js
    // Create a new Web Worker from the worker.js file
    const myWorker = new Worker('worker.js');
    // Handle messages received from the Web Worker
    myWorker.onmessage = function (e) {
      console.log('Received result from Web Worker:', e.data);
    };
    // Send data to the Web Worker for processing
    const dataToProcess = /* my data here */;
    myWorker.postMessage(dataToProcess);

    Step 3: Handle Communication Between Main Thread and Web Worker

    In both the main script and the Web Worker, I’ll use the postMessage and onmessage events to send and receive messages.

    Step 4: Terminating the Web Worker (Optional)

    I can use the terminate method to terminate a Web Worker when it's no longer needed.

    // main.js
    // Terminate the Web Worker
    myWorker.terminate();

    Step 5: Set up a Local Server (Optional)

    If I am working locally, setting up a local server to avoid cross-origin issues when loading the Web Worker file is beneficial. I can use tools like http-server or live-server for this purpose.

    # Install http-server globally
    npm install -g http-server
    # Navigate to my project folder and run
    http-server

    Step 6: Test my application

    I will open my HTML file in a web browser and see the results logged in the console. The Web Worker will handle the heavy processing tasks in the background, making the main thread responsive.

    By following these steps, I can effectively create and use Web Workers in JavaScript to optimize the performance of my web applications.

    Implementing JavaScript Web Workers in Projects

    In practical projects, Web Workers in Javascript can significantly enhance the performance of my web applications by offloading resource-intensive tasks to separate threads.

    Let's consider a real-world Javascript web worker example where I’ll be implementing Web Workers for parallel processing.

    Example Code Script:

    I will create a Web Worker File (worker.js):

    // worker.js
    onmessage = function (e) {
      const result = processData(e.data);
      postMessage(result);
    };
    function processData(data) {
      // Perform complex computations or data processing
      // ...
      return processedData;
    }

    And then integrate Web Worker in Main Script (main.js):

    // main.js
    const myWorker = new Worker('worker.js');
    myWorker.onmessage = function (e) {
      console.log('Received result from Web Worker:', e.data);
    };
    const dataToProcess = /* my data here */;
    myWorker.postMessage(dataToProcess);

    Integration Tips:

    • Data Serialization: I must ensure the data I send to the Web Workers js is serializable to avoid message passing. I will use JSON.stringify() for complex objects.
    • Avoid DOM Access: Web Workers do not have direct access to the DOM. These are most appropriate for non-DOM tasks such as data processing. They report results back to the main thread for DOM manipulations.
    • Browser Compatibility: I will always ensure Web Workers API support on my target browsers. Modern browsers fully support Web Workers. However, it is advisable to check for compatibility.
    • Local Server Setup: If I am working locally, I use a local server to prevent cross-origin problems when loading the Web Worker file.

    Using these practical examples and integration tips, I can conveniently incorporate JavaScript worker threads into my projects, improving my performance and making my site more responsive.

    Multithreading in JavaScript with Web Workers

    Multithreading in JavaScript with Web Workers
    blog.logrocket

    I, as a JavaScript developer, can use Web Workers for multithreading purposes to enhance web application performance, enabling parallel processing. Here's a brief section on Javascript multithreading Web Workers:

    1. Understanding Web Workers: Web Workers, which are like JavaScript scripts running in the background away from the main execution thread. These allow for simultaneous processing by working on various tasks simultaneously, which does not slow down the main thread during resource-consuming operations.

    2. Creating a Web Worker: I will create a separate JavaScript file for my Web Worker, for example, worker.js.

    // worker.js
    onmessage = function (e) {
      // Handle data received from the main thread
      const result = processData(e.data);
      // Send the result back to the main thread
      postMessage(result);
    };
    function processData(data) {
      // Perform heavy computations or data processing
      // ...
      return processedData;
    }

    3. Instantiating and Communicating with Web Worker: I will create a new Web Worker using the Worker constructor in my main JavaScript file.

    // main.js
    const myWorker = new Worker('worker.js');
    myWorker.onmessage = function (e) {
      console.log('Received result from Web Worker:', e.data);
    };
    const dataToProcess = /* my data here */;
    myWorker.postMessage(dataToProcess);

    4. Communication Between Threads:

    I will use the postMessage and onmessage events to send and receive messages between the main thread and the Web Worker.

    5. Concurrency and Parallel Processing:

    To achieve true parallelism and avoid UI freezing, I can consider using Web Workers to perform computationally intensive tasks like large data processing or complex calculations.

    6. Considerations:

    I use JSON.stringify() to ensure that the data passed between the main thread and the Web Worker will be serializable.

    I must always remember that Web Workers in JavaScript cannot directly refer to and manipulate the DOM; the results should be posted back to the main thread for DOM operations.

    7. Testing and Optimization:

    I will run the application with parallel processing to ensure it improves performance. Then optimize the number of Web Workers and the size of tasks according to the application’s requirements.

    Using Web Workers in my JavaScript projects can introduce multithreading and make my application more responsive.

    Error Handling in Web Workers: Common Issues and Solutions

    Like any other part of a JavaScript app, Web Workers can make mistakes just like others. Knowing usual problems and putting good mistake handling into practice is very important for the creation of strong and dependable programs by us developers. Here are some common errors and how to handle them:

    Data Serialization Issues:

    • Problem: Web Workers use message sending, but not all data types can be sent directly.
    • Solution: I will make sure that the data I send to a Web Worker can be changed back and forth, usually using JSON. I will change big things into JSON format using 'JSON.stringify()' before sending them to the worker.

    Access to DOM:

    • Problem: Web Workers can't directly reach the Document Object Model (DOM). Thus, if I try to change the DOM directly from a worker, it will lead to an error.
    • Solution: I will pass the results to the main thread using a message and manage how you change things on your domain in that big central one.

    Cross-Origin Issues:

    • Problem: If I load a Web Worker from another source, it might cause cross-origin problems.
    • Solution: If I’m working close by, I will make a local server to stop problems with different origins. I will make sure the server holding the worker script has all the needed CORS headers in place as well.

    Limited Browser Support:

    • Problem: Web Workers work well in most modern browsers, but some old or rare ones might not support them fully.
    • Solution: I will make sure my browser can work with Web Workers before I depend on them. I will also make backup plans or different answers for people using browsers that are not supported.

    Unhandled Errors in Workers:

    • Problem: Mistakes that happen in a Web Worker without proper care are not seen. This makes it difficult for me to fix them.
    • Solution: I will put a try-catch block in the Web Worker script to catch and write down mistakes. I will also use the onerror event in the main thread to catch mistakes that workers can't fix.

    Terminating Workers:

    • Problem: Not stopping a Web Worker when I don't need it anymore can also cause wasting of resources.
    • Solution: I will directly use the stop method with the Web Worker object when not needed anymore, so it can free resources.

    By fixing these usual mistakes, we software makers can improve the trustworthiness and speed of apps that use Web Workers. By making sure mistakes are dealt with carefully, we help make life easier for users and make fixing problems simpler while the program is being made.

    JavaScript Web Worker Limitations 

    A web worker is a powerful tool; however, it has a few limitations: 

    • It cannot directly manipulate the DOM. 
    • It has limited access to methods and properties of the window object. 
    • It cannot be run directly from the filesystem. It can only be run via a server. 

    Are you looking forward to learning JavaScript from scratch? Check out the Full Stack Java course from KnowledgeHut, and pick the right one that best suits your interest. 

    Conclusion

    Kudos! In this tutorial, you have learned what a web worker is, what is the need to implement a web worker in today’s world of complex web apps, how to send messages between the two threads, what are the limitations of JavaScript as a scripting language. 

    The Web Worker approach can help complex web apps overcome this limitation and open a whole new world of possibilities with seamless user experience and smooth workflow. We can’t wait to see what you build with this enormous power of shifting threads and making the user experience smooth and best for the client. Keep learning always and get ready to explore more. 

    In this article, you will learn about web workers in JavaScript, Now it's your turn to give your single-threaded JavaScript multi-thread functionalities using web workers. 

    Frequently Asked Questions (FAQs)

    1What is a Web Worker Used For?

    Web Workers usually do offload tasks. They are used to offload the main thread so that it can be used for other tasks that need immediate action. 

    • It can be used to perform some CPU-intensive work. 
    • It's also used for polling URLs in the background. 
    • In online code editors, it's used in syntax highlighting. 
    2Is Web Worker a Thread?
    Web workers are means through which you can add multi-threading functionality in your JavaScript code. 
    3How Many Web Workers can Run Concurrently JavaScript?

    This totally depends upon the user’s system. The browser creates one thread per tab. The main thread can create an unlimited number of web workers until the user's system resources are fully consumed.

    4What is the Difference Between Service Workers and Web Workers?

    Service workers allow users to detect network requests via the fetch event and to listen for Push API events in the background via the push event. A web worker can’t do this.

    5How Do I Debug a Web Worker?

    We can use chrome debugger tools to debug web workers. The chrome web browser support or any other famous web browser used by developers has developer tools built-in it. You can use that to debug your web worker.

    Profile

    Bala Krishna Ragala

    Blog Author

    Bala Krishna Ragala, Head of Engineering at upGrad, is a seasoned writer and captivating storyteller. With a background in EdTech, E-commerce, and LXP, he excels in building B2C and B2B products at scale. With over 15 years of experience in the industry, Bala has held key roles as CTO/Co-Founder at O2Labs and Head of Business (Web Technologies) at Zeolearn LLC. His passion for learning, sharing, and teaching is evident through his extensive training and mentoring endeavors, where he has delivered over 80 online and 50+ onsite trainings. Bala's strengths as a trainer lie in his extensive knowledge of software applications, excellent communication skills, and engaging presentation style.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon