Advantages of Web workers
- Web workers operate independently of the main browser UI thread.
- Ideal for running computationally expensive tasks in background threads without affecting the UI thread.
- Parallel processing for better application performance.
- Web workers live in a restricted and thread-safe environment.
Basic web worker support is good across all browsers but I do not recommend using shared web workers as the support is very limited.
Basic web worker support:
- Safari Mobile 5.1
- Android 4.4
- Chrome 4
- IE 10
Worker thread DO NOT have access to:
- Window object
- Document object
- Parent object
- Global variables or functions in main page
Also note that all of your worker scripts must be served from the same domain and protocol as the script that is attempting to create the worker.
###Ideal Candidates/Use cases
The most important thing is to identify and isolate hot spots in your code so that they can me moved to web workers for parallel execution provided they do not have any limitations mentioned above.
The following is a sample web worker which loads and parses JSON file.
Add the following to your build.hxml to generate worker script file:
The following sample shows how to load and communicate with the worker script.
Note that web workers are not automatically garbage collected and will live until you manually terminate them.
You can also terminate the worker by calling
close() method on itself.
You can check my repo for more samples.
Any questions or comments, please post them in the comments section below. Thanks for reading.