docs/src/routes/sveltekit/index.mdx
SvelteKit uses Vite to build, so we can use partytownVite.
src/routes/+layout.svelteAdopting this strategy from the Partytown + Vite docs:
// vite.config.js
import { join } from "path";
import { sveltekit } from "@sveltejs/kit/vite";
import { partytownVite } from "@qwik.dev/partytown/utils";
/** @type {import('vite').UserConfig} */
const config = {
plugins: [sveltekit(), partytownVite()],
};
export default config;
src/routes/+layout.svelteAdapting from the HTML integration guide
// src/routes/+layout.svelte
<script>
import { partytownSnippet } from '@qwik.dev/partytown/integration'
</script>
<svelte:head>
{@html '<script>' + partytownSnippet() + '</script>'}
</svelte:head>
This is where we use partytown to add those scripts (note type="text/partytown" below). If your script declares global functions or variables, make sure they are explicitly declared with window and forwarded to the web worker.
This example shows Google Tag Manager. Note window.gtag = function() instead of function gtag().
Putting it together with the previous changes, our +layout.svelte looks like:
// src/routes/+layout.svelte
<script>
import { partytownSnippet } from '@qwik.dev/partytown/integration'
</script>
<slot />
<svelte:head>
<script>
// Forward the necessary functions to the web worker layer
partytown = {
forward: ['dataLayer.push', 'gtag']
};
</script>
{@html '<script>' + partytownSnippet() + '</script>'}
<script type="text/partytown" src="https://www.googletagmanager.com/gtag/js?id=YOUR-ID-HERE"></script>
<script type="text/partytown">
window.dataLayer = window.dataLayer || [];
window.gtag = function(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'YOUR-ID-HERE');
</script>
</svelte:head>
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.
Acknowledgements: credit belongs to monogram.io for an earlier version of this guide.