diff --git a/src/components/analytics/AnalyticsScripts.tsx b/src/components/analytics/AnalyticsScripts.tsx index 0c19fc3..ee1e6c2 100644 --- a/src/components/analytics/AnalyticsScripts.tsx +++ b/src/components/analytics/AnalyticsScripts.tsx @@ -1,6 +1,7 @@ "use client"; import Script from "next/script"; +import { useEffect, useMemo, useRef } from "react"; interface AnalyticsData { facebook_pixel?: string[]; @@ -13,6 +14,13 @@ interface AnalyticsScriptsProps { externalId?: string; // visitorId from fingerprint - used for matching across Pixel and CAPI } +// Declare fbq for TypeScript +declare global { + interface Window { + fbq?: (...args: unknown[]) => void; + } +} + /** * Компонент для инъекции аналитических скриптов через next/script * @@ -25,19 +33,45 @@ interface AnalyticsScriptsProps { * - Лучшая производительность через оптимизации Next.js */ export function AnalyticsScripts({ data, externalId }: AnalyticsScriptsProps) { + const facebookPixels = useMemo(() => data?.facebook_pixel || [], [data?.facebook_pixel]); + const googleAnalyticsIds = data?.google_analytics || []; + const yandexMetrikaIds = data?.yandex_metrica || []; + + // Track which pixels have been initialized with external_id + const initializedPixelsRef = useRef>(new Set()); + + // Initialize FB Pixel when externalId becomes available + useEffect(() => { + if (!externalId || facebookPixels.length === 0) return; + + // Wait for fbq to be available + const initPixels = () => { + if (!window.fbq) { + // SDK not loaded yet, retry in 100ms + setTimeout(initPixels, 100); + return; + } + + facebookPixels.forEach((pixelId) => { + if (initializedPixelsRef.current.has(pixelId)) return; + + window.fbq!("init", pixelId, { external_id: externalId }); + window.fbq!("track", "PageView"); + initializedPixelsRef.current.add(pixelId); + }); + }; + + initPixels(); + }, [externalId, facebookPixels]); + if (!data) return null; - const facebookPixels = data.facebook_pixel || []; - const googleAnalyticsIds = data.google_analytics || []; - const yandexMetrikaIds = data.yandex_metrica || []; - return ( <> - {/* Facebook Pixel Scripts */} - {facebookPixels.map((pixelId) => ( + {/* Facebook Pixel SDK - loads immediately, init happens in useEffect when externalId ready */} + {facebookPixels.length > 0 && (