SvelteKit
SvelteKit uses Vite to build, so we can use partytownVite
.
- Add the Partytown script to
src/routes/+layout.svelte
- Copy the Partytown files to the local filesystem using the Vite plugin
- Optional: reverse-proxying scripts
- Optional:
svelte-preprocess
configuration - Then adding 3rd party scripts
1. Add the Partytown script to src/routes/+layout.svelte
Adapting from the HTML integration guide
// src/routes/+layout.svelte
<script>
import { partytownSnippet } from '@builder.io/partytown/integration'
</script>
<svelte:head>
<!-- Config options -->
<script>
// Forward the necessary functions to the web worker layer
partytown = {
forward: ['dataLayer.push']
}
</script>
{@html '<script>' + partytownSnippet() + '</script>'}
</svelte:head>
2. Copy the Partytown files to the local filesystem using the Vite plugin
Adopting this strategy from the Partytown + Vite docs:
// vite.config.js
import { join } from 'path'
import { sveltekit } from '@sveltejs/kit/vite'
import { partytownVite } from '@builder.io/partytown/utils'
/** @type {import('vite').UserConfig} */
const config = {
plugins: [
sveltekit(),
partytownVite()
]
}
export default config
3. Optional: reverse-proxying scripts
This will only be necessary depending on which scripts you are using. The implementation will vary depending on hosting platform. See Partytown’s recommended guides.
4. Then adding 3rd party scripts
This is where we FINALLY use partytown to add those scripts (note type="text/partytown"
below). This example shows Google Tag Manager. Putting it together with the previous changes, our +layout.svelte
looks like:
// src/routes/+layout.svelte
<script>
import { partytownSnippet } from '@builder.io/partytown/integration'
</script>
<slot />
<svelte:head>
<script>
partytown = {
forward: ['dataLayer.push']
};
</script>
{@html '<script>' + partytownSnippet() + '</script>'}
<script type="text/partytown" src="https://www.googletagmanager.com/gtag/js?id=G-ZX7H2KPXNZ"></script>
<script type="text/partytown">
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-ZX7H2KPXNZ');
</script>
</svelte:head>
Acknowledgements: credit belongs to monogram.io for an earlier version of this guide.