Web Workers in Meteor?

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

1 Like

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

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

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

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

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).

2 Likes

Hi, wondering if any further thoughts on this since Meteor 1.9, it would be nice to run CPU intensive tasks in another thread.

Is there a way to compile code (ie Typescript) put in the public folder ?

use the npm package simple-web-worker. I use it extensively in a Meteor app

1 Like

That’s very elegant, thanks for the tip!