Web Workers in Meteor?

#1

Is there a way to use Web workers in Meteor ? I need to process bulk data in the background while not blocking the UI.

Many Thanks,
Beemer

#2

Yes, web workers work fine with Meteor.

The part that’s a bit different with meteor is getting a url to load the worker’s code from.

The easiest way is to put the worker script in /public/and Meteor will serve it up without compilation:

const worker = new Worker(Meteor.absoluteUrl('worker.js'))
worker.addEventListener('message', function (data) {
    //... do things
});

// then you can post messages back and forth
worker.postMessage(data)

Important to note that you won’t be able to import stuff from elsewhere in your app, this file needs to be self-contained

2 Likes
#3

Thanks ! Will try this. I was going to use the Web Worker to insert data into Minimongo. Will the Web Worker have access to that or the Meteor context ? ie. use Meteor.user() or call methods

#4

No, it won’t have access to any of that.
Especially since memory is isolated so minimongo updates in the worker would not have any effect on the minimongo in the browser (until the server processes the request and re-publishes the updated documents, at which point you could just use a method call instead of a worker)

You could try out loading the main app bundle into a webworker, but beware Here Be Dragons

#5

Thanks Coagmano, i will pass on the Web Workers then !

#6

You could always postMessage to the webworker (e.g. in a Tracker.autorun) and have it do the processing (I believe this how webworkers were designed in the first place).

1 Like