Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Svelte: Web worker in without SvelteKit

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:

  1. Add them directly to the source code (app.svelte), hence the compiler will pick it up and bundle it (at least I would assume he does so). I haven't found any code sample for that one.
  2. Link the web worker javascript file in my index.html and place it manually in the public folder.

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?

like image 935
Akantor Avatar asked Dec 29 '25 19:12

Akantor


1 Answers

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

Option 1

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');

Option 2

Just put the same line in your main.js file.

like image 138
cascading-jox Avatar answered Jan 01 '26 08:01

cascading-jox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!