Getting Started with Web Workers

The Angular 8 CLI has simplified getting started with Web Workers. To create a Web Worker, we will simply run the Angular 8 web-worker schematic.

Generate a Web Worker

The name and location of the worker are mostly arbitrary. A caveat, if your Web Worker has the same name and folder as your component, Angular will automatically add the following code to your component for you. If not, add this code where you want to use the worker.

Generated Web Worker Initialization

The only other code generated is the actual worker itself. This is where we will move our long-running computations to.

Generated Web Worker

Main thread → Web Worker → Main thread

When our Web Worker invokes worker.postMessage('hello') the content inside our 'message' event listener will execute inside the Worker. Once our task has completed, postMessage(response) will be called from the Web Worker and worker.onmessage(data)=> {} will execute inside our component back in the Main thread.

Long-running task in Web Worker

Web Worker Performance

Once we move our long-running task to the Web Worker inside of addEventListener('message', (data)=> { // Here }); we will be ready to test our performance again. Note, we will cover various limitations when executing code in a Web Worker later. For now, we simply move our code from the component to the Web Worker.

We can see that the performance of our application on start-up has significantly improved. This is because the Main thread only takes 1.8s before its finished evaluating our Javascript and rendering our components on the screen.

When our long-running task was in the Main thread, we had to wait the additional time to complete the long-running task before the application became interactive.