We are planning to use web workers in an ionic 2 application. However ionic 2 uses ionic-app-scripts (https://github.com/ionic-team/ionic-app-scripts, we are using version 1.0.0) with webpack. We need to have a webworker typescript file that is compiled to JS but NOT bundled with the other files as main.js.
What we had in mind was to have a file name format such as
servicetest.worker.ts where the ".worker" file extension part will be identified and compiled from typescript to javascript but not bundled along with the other files.
Any advice on this is much appreciated as it seems that we have to customize the appscripts.
Kind of a really late answer but perhaps it may help someone else. Take a look at https://www.javascripttuts.com/how-to-use-web-workers-with-ionic-in-one-go/
I followed that article but had to make some adjustments because I had to call a worker method on demand, not on the constructor.
On the ./src/assets folder create a new folder called workers where your worker.JS files will live. Yes JS not TS, as far as I know TypeScript files won't compile to an usable webworker.
Create a webworker. I'll paste the main code of my fuzzySearch webworker (./assets/workers/fuzzysearch-worker.js):
'use strict';
var pattern, originalList;
self.onmessage = function(event) {
// Receive a message and answer accordingly
pattern = event.data.pattern;
originalList = event.data.originalList;
self.doFuzzySearch();
};
self.doFuzzySearch = function() {
var filteredList;
console.time('internalFastFilter');
filteredList = self.fastFilter(originalList, (item) => self.hasApproxPattern(item.searchField, pattern));
console.timeEnd('internalFastFilter');
// Send the results back
postMessage({ filteredList: filteredList });
};
// The code above is purposely incomplete
On your .ts file declare the worker variable (usually above the constructor):
private readonly searchWorker: Worker = new Worker('./assets/workers/fuzzysearch-worker.js');
On the constructor:
constructor(/* Other injected dependencies here */
public ngZone: NgZone) {
this.searchWorker.onmessage = (event) => {
// Inside ngZone for proper ChangeDetection
this.ngZone.run(()=> {
this.dataList = event.data.filteredList;
console.timeEnd('searchWorker');
})
};
}
Finally, on your "action function", lets say doSearch:
doSearch(event) {
// ... extra code to do some magic
console.time('searchWorker');
this.searchWorker.postMessage({ command: 'doFuzzySearch', originalList: this.realList, pattern: searchFilter });
// ... extra code to do some other magic
}
this.searchWorker.postMessage makes the call. All heavy loading operations are resolved inside the webworker.
Hope it helps. Best regards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With