Lesson 17

Using Web Workers for Heavy Lifting

Offload heavy processing to web workers for increased performance

PRO

Lesson Outline

Using Web Workers for Heavy Processing

All of the "work" the browser performs for our application - scripting, rendering, painting, compositing - all happens on a single "thread". If you are not familiar with the concept of a "thread" in terms of computing, you can think of a single thread as being a single employee doing a job.

You could give a single employee 10 different tasks to do at the same time, and that employee could spend a little bit of time working on one thing and a little bit of time on another, but at any single point in time, they can only be performing one task. You could ask them to guard the door and to prepare a report, and the employee could switch back and forth between those tasks, but they can only ever do one at any single point in time.

It's the same with the browser trying to render our application. The browser does a bit of scripting, a bit of layout calculation, a bit of painting, and it switches between these tasks rapidly creating the illusion that it's just doing everything at once. But as we have seen in our performance tests, it is only ever actually doing one thing at a time, one thing after the other.

A web worker allows us to add a second "employee" into the mix. The web worker exists independently from the main thread of the application. The main browser thread can be working on one thing, and the web worker can be working on something else at the same time (we could even have multiple web workers running).

Unfortunately, we can't just "turbocharge" our application with web workers because it allows us to create a bunch of different "threads". The downside to using a web worker is that it has absolutely no access to the DOM, which means that we can't use them for a lot of things we might want to do in our Ionic applications.

A web worker exists in its own little universe. What we can do is send data back and forth between the main thread and the web worker using messages. This makes web workers ideal for performing heavy processing/computations that don't need to interact with the DOM.

Performing Heavy Processing in the Main Thread

To demonstrate where a web worker may be useful, we will take a look at an example. I've set up an application with a simple list and a provider. That provider contains a function called doSort which looks like this:

PRO

Thanks for checking out the preview of this lesson!

You do not have the appropriate membership to view the full lesson. If you would like full access to this module you can view membership options (or log in if you are already have an appropriate membership).