Hacker News new | ask | show | jobs
by ridiculous_fish 3398 days ago
I used WebWorkers for some math - basically lots of Fourier transforms, which took a few seconds to complete.

I expected to instantiate a WebWorker with a function, and was surprised to discover you have to give it a separate JavaScript file. It is not easy to adopt.

1 comments

You can just call toString on a function and Blob the string. You have to keep your head straight about the fact that scopes won't transfer (no closures), which is probably why the API doesn't do it for you.
Yeah, this ticked me off as well because the use of Web Workers feels extremely un-idiomatic, but what you've said makes sense. If you just passed a function it might dupe people into thinking closures would work or, and this is perhaps worse, force the standard down the route of copying all the values available in the current closure into the worker's scope, which just sounds like a terrible idea to me.
This didn't work in my case because I had references to other functions, for complex number handling and the like. I ended up just loading the whole minified .js file again in the Worker, which worked though it felt ridiculous.
One of the native functions available in a web worker is importScript - it allows to load include other scripts (eg lodash) into the worker scope.
I wonder if bundlers like WebPack could make life simpler here..
It really really does. Webpack's worker stuff make it so stupid simple that i was kicking myself for not using it a long time ago.