> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kameleoon.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Implementation with SvelteKit

> Integrate Kameleoon with anti-flicker protection and execute the engine.js script after SvelteKit hydration.

# Implementation with SvelteKit

Integrate **Kameleoon Web Experimentation** with **anti-flicker protection** and execute the `engine.js` script **after SvelteKit hydration**. This setup ensures optimal performance, visual stability, and compatibility with the SvelteKit rendering lifecycle.

### Access the production-ready SvelteKit integration

Access the production-ready repository here:
[https://github.com/Kameleoon/setup-engine-sveltekit](https://github.com/Kameleoon/setup-engine-sveltekit)

Before starting, **replace the sitecode value** in [`src/lib/integrations/Kameleoon/sitecode.ts`](https://github.com/Kameleoon/setup-engine-sveltekit/blob/main/src/lib/integrations/Kameleoon/sitecode.ts).

## Script Domain

Your Kameleoon script domain may differ between projects. Depending on when you created your project, your scripts may reside on `kameleoon.eu` or `kameleoon.io`. Always use the domain displayed for your project in the Kameleoon App.

***

## Overview

1. **Preload the Kameleoon engine**: Ensure the browser downloads and caches the engine early.
2. **Apply anti-flicker CSS**: Hide content until the engine is ready to prevent layout shifts.
3. **Run the engine after hydration**: Execute the script after SvelteKit hydration to avoid mismatches.

***

## Components

The integration uses **two components** to ensure smooth loading and prevent flickering during hydration.

***

### 1. Server component

The component:

* Injects anti-flicker CSS during SSR to prevent UI flashing.
* Preloads the `engine.js` file so downloading starts as soon as possible.

```tsx theme={null}
<script lang="ts">
  import { SITECODE_SRC } from './sitecode';
</script>

<svelte:head>
  <link
    rel="preload"
    href={SITECODE_SRC}
    as="script"
    fetchpriority="high"
  />

  <style id="kameleoonLoadingStyleSheet">
    html::after {
      content: '';
      position: fixed;
      inset: 0;
      background: #fff;
      z-index: 2147483647;
    }
  </style>
</svelte:head>
```

See [`KameleoonHead.svelte`](https://github.com/Kameleoon/setup-engine-sveltekit/blob/main/src/lib/integrations/Kameleoon/KameleoonHead.svelte) on GitHub.

***

### 2. Client component

The component:

* Removes the anti-flicker styles after hydration.
* Loads the Kameleoon `engine.js` script dynamically.
* Ensures the script loads without blocking rendering.

```tsx theme={null}
<script lang="ts">
  import { onMount } from 'svelte';
  import { SITECODE_SRC } from './sitecode';

  // custom value
  const kameleoonLoadingTimeout = 500;

  function removeAntiflickerStyles(): void {
    window.kameleoonQueue = window.kameleoonQueue || [];
    window.kameleoonStartLoadTime = Date.now();

    window.kameleoonDisplayPage = (fromEngine?: boolean): void => {
      if (!fromEngine) {
        window.kameleoonTimeout = true;
      }
      document
        .getElementById('kameleoonLoadingStyleSheet')
        ?.remove();
    };

    window.kameleoonDisplayPageTimeOut = setTimeout(
      window.kameleoonDisplayPage,
      kameleoonLoadingTimeout
    );
  }

  function loadEngine(): void {
    if (document.getElementById('kameleoon-engine')) return;

    const script = document.createElement('script');
    script.src = SITECODE_SRC;
    script.async = true;
    script.id = 'kameleoon-engine';
    document.head.appendChild(script);
  }

  
  // Execute Kameleoon after hydration
  onMount(() => {
    removeAntiflickerStyles();
    loadEngine();
  });
</script>
```

See [`KameleoonHydrationReady.svelte`](https://github.com/Kameleoon/setup-engine-sveltekit/blob/main/src/lib/integrations/Kameleoon/KameleoonHydrationReady.svelte) on GitHub.

<Note>
  The default anti-flicker timeout is `750 ms`. Adjust `kameleoonLoadingTimeout` if needed.
</Note>

***

## Usage in RootLayout

Combine both components in your layout:

```tsx theme={null}
<script lang="ts">
  import KameleoonHead from '$lib/integrations/Kameleoon/KameleoonHead.svelte';
  import KameleoonHydrationReady from '$lib/integrations/Kameleoon/KameleoonHydrationReady.svelte';
</script>

<!-- SSR head injection -->
<KameleoonHead />

<!-- Optional: other head tags -->
<svelte:head>
  <link rel="preconnect" href="https://fonts.googleapis.com" />
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="anonymous" />
</svelte:head>

<!-- Client bootstrap after hydration -->
<KameleoonHydrationReady />

<slot />
```

See [`layout.svelte`](https://github.com/Kameleoon/setup-engine-sveltekit/blob/main/src/routes/%2Blayout.svelte) on GitHub.

***

## Key Takeaways

* Protect against flickering on SSR.
* Use hydration-aware script execution.
* Load the engine asynchronously.
* Use a fallback timeout for reliability.
* Avoid blocking scripts.
* Support SvelteKit layouts, SSR, and client-side routing.

With this setup, your SvelteKit application loads Kameleoon efficiently and avoids hydration-related issues.
