Using Web Workers in Ionic App
JavaScript processes are unique in that it runs on a single thread and within this thread, every single process is executed.
Within an Ionic Angular project for example, you may have the user interaction part running alongside the part where an important calculation for complex cryptography is being calculated, for example. Both are running on the same thread. This is fine, but this can be further optimized.
There is a way to separate the user interaction part, responsible for updating the UI, and other processes that could run on a separate thread altogether, running alongside the main thread. This method is generally known as web workers.
Heavy computations, calculations or executing time consuming tasks can be done on a separate thread, leaving the main thread running smoothly with maximum efficiency to handle user interaction matters.
Here is a step by step on how to build an Ionic Angular app with web workers running alongside the main thread.
Step 0: Start an Ionic Angular Project
If you have not had the chance to give Ionic a try, please do, as it is one of the most simplest way to get into mobile app development with web based skills like HTML, TypeScript/JavaScript and CSS. Check out Ionic’s website
Step 1: Create a web worker JavaScript file and place it inside the assets folder
So here’s the web worker JavaScript file. In the interest of simplicity, it will be just a simple function to calculate the sum of two numbers. Of course, if you want to do complex calculation, this is where you need to do it. The result is then returned with postMessage function:
Step 2: Execute the web worker in the TypeScript file
Here’s my home.page.ts file in full, where I execute the web worker and console log its value:
Conclusion
There you go. That is it. The main thread will continue providing user interaction without needing to worry about the calculation that is being executed by the web worker in a separate thread. The main thread itself is optimized, the users are happy and this process maximizes the efficiency of your application.
Do give it a try.
More content at PlainEnglish.io.
Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.
Interested in scaling your software startup? Check out Circuit.