147 lines
5.0 KiB
TypeScript
147 lines
5.0 KiB
TypeScript
'use client';
|
|
|
|
import { useEffect, useRef } from 'react';
|
|
import { usePathname } from 'next/navigation';
|
|
|
|
declare global {
|
|
interface Window {
|
|
dataLayer?: any[];
|
|
clarity?: any;
|
|
gtag?: (...args: any[]) => void;
|
|
}
|
|
}
|
|
|
|
interface AnalyticsDeferredProps {
|
|
gtmId?: string;
|
|
gaId?: string;
|
|
clarityId?: string;
|
|
}
|
|
|
|
export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsDeferredProps) {
|
|
const pathname = usePathname();
|
|
const loadedRef = useRef(false);
|
|
const initialPathRef = useRef<string | null>(null);
|
|
|
|
useEffect(() => {
|
|
if (!initialPathRef.current && pathname) {
|
|
initialPathRef.current = pathname;
|
|
}
|
|
}, [pathname]);
|
|
|
|
// Track client-side page views on Next.js route transitions
|
|
useEffect(() => {
|
|
if (!pathname || !loadedRef.current) return;
|
|
if (pathname === initialPathRef.current) return;
|
|
|
|
// 1. Google Analytics 4 page_view event on client navigation
|
|
if (gaId && typeof window !== 'undefined' && typeof window.gtag === 'function') {
|
|
window.gtag('event', 'page_view', {
|
|
page_path: pathname,
|
|
page_location: window.location.href,
|
|
page_title: typeof document !== 'undefined' ? document.title : '',
|
|
});
|
|
}
|
|
|
|
// 2. Google Tag Manager page_view event on client navigation
|
|
if (gtmId && typeof window !== 'undefined' && Array.isArray(window.dataLayer)) {
|
|
window.dataLayer.push({
|
|
event: 'page_view',
|
|
page_path: pathname,
|
|
});
|
|
}
|
|
}, [pathname, gaId, gtmId]);
|
|
|
|
useEffect(() => {
|
|
let loaded = false;
|
|
|
|
const loadAnalytics = () => {
|
|
if (loaded) return;
|
|
loaded = true;
|
|
loadedRef.current = true;
|
|
|
|
// Clean up event listeners
|
|
window.removeEventListener('scroll', loadAnalytics);
|
|
window.removeEventListener('touchstart', loadAnalytics);
|
|
window.removeEventListener('mousemove', loadAnalytics);
|
|
window.removeEventListener('keydown', loadAnalytics);
|
|
|
|
// 1. Google Tag Manager
|
|
if (gtmId) {
|
|
window.dataLayer = window.dataLayer || [];
|
|
window.dataLayer.push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' });
|
|
const gtmScript = document.createElement('script');
|
|
gtmScript.async = true;
|
|
gtmScript.src = `https://www.googletagmanager.com/gtm.js?id=${gtmId}`;
|
|
document.head.appendChild(gtmScript);
|
|
}
|
|
|
|
// 2. Google Analytics 4 (ensures GA4 hits fire directly even if GTM container lacks GA4 config tag)
|
|
if (gaId) {
|
|
window.dataLayer = window.dataLayer || [];
|
|
function gtag(..._args: any[]) {
|
|
// Note: Google's gtag.js specifically expects the native `arguments` object.
|
|
// Pushing an ES6 Array causes gtag.js to silently ignore tracking commands.
|
|
window.dataLayer?.push(arguments);
|
|
}
|
|
window.gtag = gtag;
|
|
gtag('js', new Date());
|
|
gtag('config', gaId, { page_path: window.location.pathname });
|
|
|
|
// Only append gtag.js script if not already added
|
|
if (!document.querySelector(`script[src*="${gaId}"]`)) {
|
|
const gaScript = document.createElement('script');
|
|
gaScript.async = true;
|
|
gaScript.src = `https://www.googletagmanager.com/gtag/js?id=${gaId}`;
|
|
document.head.appendChild(gaScript);
|
|
}
|
|
}
|
|
|
|
// 3. Microsoft Clarity
|
|
if (clarityId) {
|
|
(function (c: any, l: any, a: any, r: any, i: any) {
|
|
c[a] =
|
|
c[a] ||
|
|
function (...args: unknown[]) {
|
|
(c[a].q = c[a].q || []).push(args);
|
|
};
|
|
const t = l.createElement(r);
|
|
t.async = 1;
|
|
t.src = 'https://www.clarity.ms/tag/' + i;
|
|
const y = l.getElementsByTagName(r)[0];
|
|
if (y?.parentNode) y.parentNode.insertBefore(t, y);
|
|
else l.head.appendChild(t);
|
|
})(window, document, 'clarity', 'script', clarityId);
|
|
}
|
|
};
|
|
|
|
// Listen to first user interaction
|
|
window.addEventListener('scroll', loadAnalytics, { passive: true, once: true });
|
|
window.addEventListener('touchstart', loadAnalytics, { passive: true, once: true });
|
|
window.addEventListener('mousemove', loadAnalytics, { passive: true, once: true });
|
|
window.addEventListener('keydown', loadAnalytics, { passive: true, once: true });
|
|
|
|
// Fallback: idle execution after 3.5s
|
|
let idleId: number | undefined;
|
|
const timer = setTimeout(() => {
|
|
if (typeof window !== 'undefined' && 'requestIdleCallback' in window) {
|
|
idleId = window.requestIdleCallback(loadAnalytics, { timeout: 2000 });
|
|
} else {
|
|
loadAnalytics();
|
|
}
|
|
}, 3500);
|
|
|
|
return () => {
|
|
loaded = true;
|
|
loadedRef.current = false;
|
|
clearTimeout(timer);
|
|
if (idleId !== undefined) window.cancelIdleCallback(idleId);
|
|
window.removeEventListener('scroll', loadAnalytics);
|
|
window.removeEventListener('touchstart', loadAnalytics);
|
|
window.removeEventListener('mousemove', loadAnalytics);
|
|
window.removeEventListener('keydown', loadAnalytics);
|
|
};
|
|
}, [gtmId, gaId, clarityId]);
|
|
|
|
return null;
|
|
}
|