Prim+RPC can be used to bridge Web Workers and Shared Workers. You may use the Web Worker as a server where functions
are placed (the most common scenario) or use the Web Worker as a client to call functions defined on the main thread. We
will cover both scenarios.
Also note that while these examples use Worker, you can just as easily swap these out for SharedWorker as Prim+RPC
supports both. A Shared Worker is useful, for instance, when sharing the same data between multiple tabs.
Whether using Prim+RPC or not, Web Worker setup can become complicated when using build tools like TypeScript and Vite.
If you get stuck, check out the Web Worker example for working code.
First, let’s set up a module to be used from whichever environment we designate as the server:
Web Worker as Server
We can set up a Web Worker as a server that will host our functions:
Now we can use this set up the module to be used from the main thread. We will pass this file as the URL to our Web
Worker. This example assumes you are using Vite to bundle your app (which includes tools to separate your worker code
into a separate bundle from your main thread) but, of course, you may use any bundler or use none at all.
From the main thread:
Now we can use this client anywhere in our app and the function will be executed inside of the Web Worker:
Web Worker as Client
Let’s set up Web Worker that can easily access functions defined on the main thread. This can be useful when your
functions in a Web Worker needs specific browser APIs only available on the main thread.
First, let’s set up the client that will run inside of the Web Worker.
And we’ll set up a file that will act as the entrypoint for our Worker:
We don’t yet have a server that can communicate with the Worker yet. Let’s set that up now:
Now in our Web Worker, we can make a call to our function defined on the main thread: