Parallel programming | Angular 8

Performance tuning for your web applications using web workers.

Image for post
Angular 8 Logo

Angular 8 was released a few months ago. I’m gonna mention the angular 8 new features before going to explain who to use web workers.

  • Preview of Ivy
  • Web Workers
  • Lazy Loading
  • Improvement of ngUpgrade

These are more like performance upgrades to compete with React. hahaha!

There are two popular ways to integrate Web Worker in your angular application:

  1. Run all the business logic of your application in a web worker thread.
  2. Run some CPU intensive business logic in a web worker thread.
    (Like a password encryption processes in the login)

I’ll explain my experience with web workers and why I wanted it. In the project that I’m working on, there are some components that have more than 8 database requests and other computational tasks in the OnInt();.So this is the result.

Image for post
Lighthouse results

This analysis was done by using Lighthouse in Chrome DevTools.

Getting Started

We can start by generating a worker component using

ng g webWorker appWorker

This will create a web worker and it will automatically configure your project to use web workers. In-app-worker.worker.ts

addEventListener(‘message’, ({ data }) => {
const response = `worker response to ${data}`;
postMessage(response);
});

to use this in your app.component.ts

if (typeof Worker !== ‘undefined’) {

const worker = new Worker(‘./app.worker’, { type: ‘module’ });
worker.onmessage = ({ data }) => {
console.log(`page got message: ${data}`);
};
worker.postMessage(‘hello’);} else {
//Some code to save you !
}

So let me give some tips and tricks to work with web workers.

  • This is more like threads in java.
  • If you pass something to the worker only a copy of that will pass.not the object. If you want to do something similar to that you can use the worker.postMessage and reassign your object.
  • If you have an object that contains some objects you can’t pass that directly. Actually, you can but there’s no use in that.
  • you have to do some deep cloning using JSON.stringify(). Then you can parse that data with JSON.parse().

Now You’re ready to use web workers. Cheers! Happy coding.No freezing!

University of Westminster • Former Software Engineering Intern — DirectFN | Mubasher • https://www.linkedin.com/in/aselsiriwardena/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store