Reputation: 1218
I am writing a Cordova app where at some point there are computations which are a bit too heavy (digital signatures). As a consequence when the button that launches those computations is clicked the UI freezes for an instant.
The computations are also javascript code, is there any way in Cordova to use a web worker or something equivalent and offload them to another thread?
Upvotes: 2
Views: 318
Reputation: 30366
You can use a web worker to do the intensve JS processing on a different thread, so you don't block the UI thread. Note: you'll need to be using a modern Webview, so Crosswalk if targeting Android 4.x (Android 5+ should be fine due to self-updated Webview).
You can do something like this:
myapp.js:
var worker = new Worker('my.worker.js');
// Receive the output from the worker when it's done
worker.addEventListener('message', function (e) {
try {
var data = e.data;
if(!data.success){
handleError(data.error);
}else{
display(data.output);
}
} catch (ex) {
handleError(ex);
}
}, false);
// Start the worker with some input
worker.postMessage({
input: "something heavy to process"
});
my.worker.js:
importScripts('lib/some.dependency.js');
// Receive the input from the main UI thread
self.addEventListener('message', function(ev) {
try{
var data = ev.data;
var input = data.input;
var output = doSomeHeavyLifting(input);
self.postMessage({
success: true,
output: output
});
}catch(ex){
self.postMessage({
success: false,
error: ex
});
}
}, false);
Upvotes: 1