I am struggling to find information how to incorporate a web worker in a Svelte app that is not using SvelteKit (I have found numerous examples how do it with SvelteKit though). Basically I would believe I have two choices here:
I would assume 1. is more elegant and the way to go, but I haven't found any clear best practices/guidelines how to implement it.
So what is the best choice and is there anywhere an example that I might be able to reuse?
I don't see why you would need to place it manually in the public folder in option 2. If you have a good build tool it should handle it and I think it's better to keep the svelte files as components and not mix some general web worker code for you app there. It might make sense to put it there if you just have one big app component for your whole website (but why not just use SvelteKit in this case?).
If you are using vite as your build tool, which is really neat btw, you simply initiate it with this syntax in your script tag (documented here):
const worker = new Worker(new URL('./worker.js', import.meta.url));
If you have some other build tool you might need to change the syntax a bit. The basic syntax is (documented here):
const worker = new Worker('./worker.js');
Just put the same line in your main.js file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With