Although this answer is coming in a little late, it might be beneficial to someone else in need.
Check out
I followed the instructions from the mentioned article but had to tweak them slightly as I needed to call a worker method on demand instead of during instantiation.
In the ./src/assets
directory, create a new folder named 'workers' where your worker files with a .js extension will reside. TypeScript files may not compile into usable web workers.
Create a web worker. Below is an excerpt from my fuzzySearch web worker's main code (
./assets/workers/fuzzysearch-worker.js
):
'use strict';
var pattern, originalList;
self.onmessage = function(event) {
// Responding to received messages
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');
// Sending back the results
postMessage({ filteredList: filteredList });
};
// The code above intentionally left incomplete
In your .ts file, declare the worker variable (usually above the constructor):
private readonly searchWorker: Worker = new Worker('./assets/workers/fuzzysearch-worker.js');
In 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');
})
};
}
Lastly, in your "action function", let's say doSearch
:
doSearch(event) {
// ... additional code to perform some operations
console.time('searchWorker');
this.searchWorker.postMessage({ command: 'doFuzzySearch', originalList: this.realList, pattern: searchFilter });
// ... additional code to do more operations
}
this.searchWorker.postMessage
initiates the call. All intensive processing tasks are handled within the web worker.
Hope this provides assistance.
Warm regards.