Hacker News new | ask | show | jobs
by fenomas 1050 days ago
Hi, I appreciate the advice in general, but in my case it's not an architectural matter. Basically, I just have one internal, encapsulated function that ought to run in a worker, and I'd like to implement that without doing anything hairy - and without imposing requirements on the end-user to make their own worker. It seems like this isn't possible, but if you know of a way I'd love to hear it!
2 comments

Hey, so we're doing something similar to the solution given above, but without compiling the worker at bundle time.

Basically what we're doing is putting the worker code in a string. When you need the worker, you can `import myWorker from ./worker`. At runtime you can create a `Blob` from the string, then create a URL for it using `window.URL.createObjectURL`.

It's certainly far from ideal. Since the code lives in a string, there are no compile time errors at all (though you could probably develop without the string form and put it in a string after). But it kinda works. Hope it's what you're looking for.

Yes, data URI & blobs is a way. You can author worker code as you would normally do (in TypeScript, for example) and bundle (with type checks) it into a string as part of your own build process. Ideally, though, you would want to keep the worker wrapper separate from core library so that users with complex projects can integrate it in their own build however they want…
You can create workers at runtime. Take the fact that it is not straightforward, and hence you need to be asking this question, as a hint that it’s almost certainly the wrong thing to do for your library—unless it is specifically about something like worker management, in which case you would not be asking this question. Don’t mess with the environment, users (and future you) will thank you for it.