Using Partytown to load third-party scripts in SolidStart
Partytown provides a novel approach to load third-party scripts such as analytics in the background using web workers. This offloads non-essential scripts off the main thread speeding up your web app. This does not come without trade-offs though.
Getting Started
Create a new SolidStart project.
Install Partytown.
Configuring Partytown
We need to serve Partytown’s scripts. Partytown provides a Vite plugin to copy files to our public folder serve them during development from Vite’s dev server, however I ran into issues with this approach with some deployment presets. A Nitro module similar to @nuxtjs/partytown
would probably be ideal.
Instead of the Vite plugin, I opted for the low tech approach. I added a script to my package.json
to copy the files during build step. Be sure to run the script once locally to generate the files in development.
Additionally I added the Partytown folder to my .gitignore
so it is not committed to my repo.
You can run pnpm run build
to build your project and see the Partytown scripts in your public folder, .output/public/~partytown
.
Next we need to load Partytown’s scripts in our app. To do this we can use <Assets>
from Solid to add the scripts to our head.
With Partytown, setting a <script>
type to "text/partytown"
will tell Partytown to run the script.
You should see “Hello from Partytown!” in your console.
Using Partytown
Now that we have Partytown setup we can use it to run our code in a web worker. A common usecase for this is for analytics. Here is an example using Google Analytics with forwarding events.
Inspect your chrome network tab and you should see the Google Analytics script being loaded from Partytown service worker as well as requests being forwarded via proxytown.