Using web workers for heavy computation
If your Angular application does a lot of computation during an action, there’s a high chance that it will block the UI thread. This will cause a lag in rendering the UI because it blocks the main JavaScript thread. Web workers allow us to run heavy computation in the background thread, thus freeing the UI thread as it is not blocked. In this recipe, we’re going to use an application that does a heavy computation in the UserService
class. It creates a unique ID for each user card and saves it into localStorage
. However, it loops a couple of thousand times before doing so, which causes our application to hang for a while. In this recipe, we’ll move the heavy computation from the components to a web worker and will also add a fallback in case web workers aren’t available.
Getting ready
The app that we are going to work with resides in start/apps/chapter12/ng-ww-perf
inside the cloned repository:
- Open...