Blog

  • Hi Guys, in this blog we will be discussing the implementation of web workers in Angular. As we all know, Javascript is single threaded, hence if we are doing some CPU intensive task then it will block the UI for that time.

     

    Then how we can do time-consuming tasks without interrupting user experience?

     

    The answer is Web Workers. We can perform time-consuming tasks inside web workers because they run in a separate thread, hence it won't interrupt the user experience.

     

    In Web workers, we can perform XML requests, data storage operations, web sockets or other operations without blocking the main browser thread. They are simple objects created using Worker constructor. You can not access DOM or window global objects inside web workers and it is a good performance booster.

     

    Web workers can be created from the main thread and can be destroyed from both ends. You can create and destroy multiple workers, all depends on you. Below code will build the worker function

    createWorker(): Worker {
    
          const workerFunction = () => {
    
            // onmessage is just the event the Worker is listening
            onmessage = (e) => {
    
              // this is what I receive
              const dataObject: any[] = e.data;
    
              dataObject.map((item: any) => {
                item.formattedName = item.lastName ? `${item.firstName} ${item.lastName}` : item.userName;
              });
    
              /*  we called
               `bind` method to ensure that the `postMessage` method is referring
               to the Worker (so, the Window object) and not to our service object
              */
              postMessage.bind(self)(['type', dataObject]);
            };
          };
    
          // converting function into a string
          const dataObj = '(' + workerFunction + ')();';
    
          // this is a BlobURL,  browser interprets as a file resource
          const blob = new Blob([dataObj]);
          const blobURL = URL.createObjectURL(blob);
          // below line will return worker to the Angular component
          return new Worker(blobURL);
      }
    

    Now we will call the above function in our angular service to build web worker.

    this.http.get(`http://url.com/data`)
        .subscribe((objects: any[]) => {
          const myWorker: Worker = this.exampleService.createWorker(clients);
        
          // now, when I'll call the `postMessage` methods, the worker
          // will start to process as previously specified
    
              myWorker.postMessage(objects);
              myWorker.addEventListener('message', (received) => {
                // here the worker achieved his task, from now on we can safely call
                // other functions 
             })
          });
        }, error => {
          // handle error, somehow... hopefully
     });
     

    So we can use web worker for synching data with the server, in that case, we can run background API call to fetch data from the server and send the data to angular.

     

    The above web worker example is used to format data received from the server. Whenever we receive data from the server we call the web worker, which will format the data without blocking the browser main thread and send data back to angular. which will reduce the browser main thread load.

Tags: Angular