> ## 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.

# Nuxt での実装

> アンチフリッカー保護付きでエンジンをプリロードし、ハイドレーション後に engine.js を実行することで、Nuxt 4 を Kameleoon Web Experimentation と統合します。

# Nuxt での実装

**Nuxt 4** を **Kameleoon Web Experimentation** と統合します。本ガイドでは、**アンチフリッカー保護** 付きで Kameleoon エンジンをプリロードし、**クライアントハイドレーション後** に `engine.js` スクリプトを実行する手順を説明します。このセットアップにより、最適なパフォーマンス、視覚的安定性、Nuxt のレンダリングライフサイクルとの互換性を保証します。

リファレンス実装にアクセスできます:

* [Nuxt 3](https://github.com/Kameleoon/setup-engine-nuxt-3)
* [Nuxt 2](https://github.com/Kameleoon/setup-engine-nuxt-2)

### 本番環境向けの Nuxt 4 統合にアクセスする

本番環境向けのリポジトリはこちらにあります:
[https://github.com/Kameleoon/setup-engine-nuxt-4](https://github.com/Kameleoon/setup-engine-nuxt-4)

開始する前に、[`integrations/Kameleoon/sitecode.ts`](https://github.com/Kameleoon/setup-engine-nuxt-4/blob/main/integrations/Kameleoon/sitecode.ts) で **sitecode の値を置き換えてください**。

<Note>
  Kameleoon プロジェクトを作成した時期によっては、スクリプトが `kameleoon.eu` または `kameleoon.io` に配置されている場合があります。常に Kameleoon App のプロジェクト設定にあるドメインを使用してください。
</Note>

***

## 概要

### ワークフロー

| フェーズ               | 説明                                 | コンポーネント                            |
| ------------------ | ---------------------------------- | ---------------------------------- |
| **SSR レンダリング**     | プリロードリンクとアンチフリッカー CSS を注入          | `KameleoonHead.vue`                |
| **クライアントハイドレーション** | Vue が DOM をハイドレートする                | —                                  |
| **ハイドレーション後**      | Kameleoon エンジンを非同期で読み込む            | `KameleoonScriptLoader.client.vue` |
| **フォールバック安全終了**    | スクリプトが失敗または停滞した場合にアンチフリッカー CSS を削除 | `KameleoonScriptLoader.client.vue` |

### クイックセットアップ

1. `integrations/Kameleoon` フォルダを Nuxt プロジェクトに追加します。
2. 両方の統合コンポーネントをレイアウトにインポートして登録します(`layouts/default.vue` を推奨)。[`default.vue` での使用](#usage-in-defaultvue) を参照してください。

***

## コンポーネント

統合では、Nuxt のレンダリングパイプラインの異なる段階で実行される **2つの Vue コンポーネント** を使用します:

| コンポーネント                            | 実行コンテキスト                  | 目的                                      |
| ---------------------------------- | ------------------------- | --------------------------------------- |
| `KameleoonHead.vue`                | **サーバーサイド (SSR)**         | ハイドレーション前にプリロードディレクティブとアンチフリッカー CSS を注入 |
| `KameleoonScriptLoader.client.vue` | **クライアントサイド (ハイドレーション後)** | エンジンスクリプトを読み込み、アンチフリッカータイムアウトを管理        |

このアプローチにより、高速なレンダリング、安定した UI 動作、Nuxt ハイドレーションとの完全な互換性を提供します。

***

### 1. `KameleoonHead.vue`

`KameleoonHead.vue` は **サーバーサイドレンダリング中にのみ** 実行されます。以下によりちらつきのない体験のためにページを準備します:

* SSR 中にアンチフリッカー CSS を注入します。
* ブラウザが早期にフェッチするように Kameleoon エンジン(`engine.js`)をプリロードします。

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

<template>
    <Head>
        <!-- preload script early -->
        <Link rel="preload" :href="SITECODE_SRC" as="script" fetchpriority="high" />

        <!-- anti-flicker CSS -->
        <Style id="kameleoonLoadingStyleSheet">
            html::after { content: ''; position: fixed; inset: 0; background: #fff; z-index: 2147483647; }
        </Style>
    </Head>
</template>
```

GitHub で [`KameleoonHead.vue`](https://github.com/Kameleoon/setup-engine-nuxt-4/blob/main/integrations/Kameleoon/components/KameleoonHead.vue) を参照してください。

***

### 2. `KameleoonScriptLoader.client.vue`

`KameleoonScriptLoader.client.vue` は **ハイドレーション後のクライアント上で** 実行されます。

このコンポーネントは:

* ページの準備が整ったらアンチフリッカースタイルシートを削除します。
* `engine.js` スクリプトを動的に読み込みます。
* 遅いスクリプト読み込みのためのタイミングとフォールバック動作を処理します。

```ts theme={null}
<script setup>
defineOptions({ name: "KameleoonScriptLoader" });

import { nextTick, onMounted } from "vue";
import { SITECODE_SRC } from "~/integrations/Kameleoon/sitecode";

onMounted(async () => {
    await nextTick();

    const kameleoonLoadingTimeout = 500;

    window.kameleoonQueue = window.kameleoonQueue || [];
    window.kameleoonStartLoadTime = Date.now();

    window.kameleoonDisplayPage = function (fromEngine) {
        if (!fromEngine) {
            window.kameleoonTimeout = true;
        }
        document.getElementById("kameleoonLoadingStyleSheet")?.remove();
    };

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

    const alreadyLoaded = document.querySelector(`script[src*="${SITECODE_SRC}"]`);
    if (!alreadyLoaded) {
        const script = document.createElement("script");
        script.src = SITECODE_SRC;
        script.async = true;
        document.head.appendChild(script);
    }
});
</script>

<template>
    <!-- nothing rendered -->
</template>
```

GitHub で [`KameleoonScriptLoader.client.vue`](https://github.com/Kameleoon/setup-engine-nuxt-4/blob/main/integrations/Kameleoon/components/KameleoonScriptLoader.client.vue) を参照してください。

<Note>
  デフォルトのアンチフリッカータイムアウトは `750 ms` です。必要に応じて `kameleoonLoadingTimeout` を調整してください。
</Note>

***

## `default.vue` での使用

レイアウトでコンポーネントを組み合わせるには、以下の例を使用してください:

```ts theme={null}
<script setup>
import KameleoonHead from "~/integrations/Kameleoon/components/KameleoonHead.vue";
import KameleoonScriptLoader from "~/integrations/Kameleoon/components/KameleoonScriptLoader.client.vue";
</script>

<template>
    <!-- SSR: preload + anti-flicker -->
    <KameleoonHead />

    <!-- Client: load script after hydration -->
    <KameleoonScriptLoader />

    <!-- Layout UI -->
    <div class="min-h-screen bg-background font-inter">
        <Navigation />

        <main class="container mx-auto px-4 py-8">
            <NuxtPage />
        </main>
    </div>
</template>
```

GitHub で [`default.vue`](https://github.com/Kameleoon/setup-engine-nuxt-4/blob/main/layouts/default.vue) を参照してください。

***

## 重要なポイント

* ハイドレーションミスマッチの警告を防ぎます。
* Kameleoon の初期化前にちらつきのない体験を保証します。
* SPA ナビゲーションを含めて、スクリプトを **1回のみ** 読み込みます。
* レイアウト、ページ、動的ルート、条件付きレンダリングとの互換性を維持します。

この設定により、Nuxt アプリケーションはレンダリングの安定性に影響を与えることなく、Kameleoon を確実に読み込んで実行します。
