Analytics fix
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
'use client'
|
||||
import { useEffect } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
|
||||
import type { AnalyticsConfig } from './types.js'
|
||||
|
||||
@@ -35,24 +35,84 @@ function injectScript(src: string) {
|
||||
document.head.appendChild(s)
|
||||
}
|
||||
|
||||
export type AnalyticsProps = {
|
||||
/**
|
||||
* Core Web Vitals mode: hold back every tag's NETWORK load until the first
|
||||
* user interaction (scroll, pointer, touch, key) or `deferTimeoutMs` after the
|
||||
* window `load` event — whichever comes first. Keeps ~100+ KiB of third-party
|
||||
* JS out of the FCP/LCP window.
|
||||
*
|
||||
* Consent is unaffected: the Consent Mode default is still pushed immediately
|
||||
* (a synchronous dataLayer push, no network), and non-Google pixels still
|
||||
* require their consent category. Defer changes WHEN a tag loads, never WHETHER.
|
||||
*
|
||||
* Trade-off: visitors who leave before interacting and before the timeout are
|
||||
* not counted (slightly fewer sessions in GA). Default false.
|
||||
*/
|
||||
defer?: boolean
|
||||
/** Fallback delay after window `load`, in ms. Default 3500. */
|
||||
deferTimeoutMs?: number
|
||||
} & AnalyticsConfig
|
||||
|
||||
const INTERACTION_EVENTS = ['scroll', 'pointerdown', 'touchstart', 'keydown'] as const
|
||||
|
||||
/** True once third-party tags may load (immediately, or per `defer` rules). */
|
||||
function useDeferredReady(defer: boolean, timeoutMs: number): boolean {
|
||||
const [ready, setReady] = useState(!defer)
|
||||
|
||||
useEffect(() => {
|
||||
if (!defer || ready) {return}
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
const fire = () => setReady(true)
|
||||
const onLoad = () => {
|
||||
timer = setTimeout(() => {
|
||||
if ('requestIdleCallback' in window) {
|
||||
window.requestIdleCallback(fire, { timeout: 1000 })
|
||||
} else {
|
||||
fire()
|
||||
}
|
||||
}, timeoutMs)
|
||||
}
|
||||
|
||||
for (const e of INTERACTION_EVENTS) {
|
||||
window.addEventListener(e, fire, { once: true, passive: true })
|
||||
}
|
||||
if (document.readyState === 'complete') {onLoad()}
|
||||
else {window.addEventListener('load', onLoad, { once: true })}
|
||||
|
||||
return () => {
|
||||
for (const e of INTERACTION_EVENTS) {window.removeEventListener(e, fire)}
|
||||
window.removeEventListener('load', onLoad)
|
||||
if (timer) {clearTimeout(timer)}
|
||||
}
|
||||
}, [defer, ready, timeoutMs])
|
||||
|
||||
return ready
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads every configured analytics / marketing tag, each respecting consent:
|
||||
*
|
||||
* - **Google (GA4 / GTM)** — loaded immediately with Consent Mode: the visitor's
|
||||
* stored choice is set as the default BEFORE the tag loads, and useConsent
|
||||
* pushes an update the moment they decide. GTM wins if both IDs are set.
|
||||
* - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — these vendors have
|
||||
* no Consent Mode, so they load ONLY after the matching category is granted
|
||||
* (marketing for Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to
|
||||
* the consent banner: accept → the tag loads immediately, no reload.
|
||||
* - **Google (GA4 / GTM)** — Consent Mode: the visitor's stored choice is set as
|
||||
* the default BEFORE the tag loads (always immediately, even with `defer`),
|
||||
* and useConsent pushes an update the moment they decide. GTM wins if both
|
||||
* IDs are set.
|
||||
* - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — no Consent Mode, so
|
||||
* each loads ONLY after its category is granted (marketing for
|
||||
* Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to the banner.
|
||||
* - **`defer`** (opt-in) — additionally waits for first interaction / idle
|
||||
* after load, for better LCP/INP. See AnalyticsProps.defer.
|
||||
*
|
||||
* All IDs are public and come from SiteIntegrations (getAnalyticsConfig), passed
|
||||
* in as props. Renders nothing. Mount once, high in the tree, INSIDE
|
||||
* <ConsentProvider> (required — it reads live consent state).
|
||||
*/
|
||||
export function Analytics(props: AnalyticsConfig) {
|
||||
export function Analytics(props: AnalyticsProps) {
|
||||
const {
|
||||
clarityProjectId,
|
||||
defer = false,
|
||||
deferTimeoutMs = 3500,
|
||||
ga4MeasurementId,
|
||||
gtmContainerId,
|
||||
linkedInPartnerId,
|
||||
@@ -62,11 +122,23 @@ export function Analytics(props: AnalyticsConfig) {
|
||||
|
||||
// Live consent state — drives the non-Google pixels.
|
||||
const { state } = useConsentContext()
|
||||
const ready = useDeferredReady(defer, deferTimeoutMs)
|
||||
const defaultConsentSet = useRef(false)
|
||||
|
||||
// --- Google: load once, Consent Mode handles gating ---
|
||||
// --- Consent Mode default: immediately, once — never deferred ---
|
||||
// No network cost, and it must precede any gtag('config') / GTM start, or
|
||||
// Google assumes "granted".
|
||||
useEffect(() => {
|
||||
if (defaultConsentSet.current) {return}
|
||||
if (!ga4MeasurementId && !gtmContainerId) {return}
|
||||
setDefaultConsent(readConsent())
|
||||
defaultConsentSet.current = true
|
||||
}, [ga4MeasurementId, gtmContainerId])
|
||||
|
||||
// --- Google: load once `ready`; Consent Mode handles gating ---
|
||||
useEffect(() => {
|
||||
if (!ready) {return}
|
||||
if (!ga4MeasurementId && !gtmContainerId) {return}
|
||||
if (gtmContainerId) {
|
||||
window.dataLayer = window.dataLayer || []
|
||||
window.dataLayer.push({ event: 'gtm.js', 'gtm.start': Date.now() })
|
||||
@@ -76,12 +148,13 @@ export function Analytics(props: AnalyticsConfig) {
|
||||
gtag('js', new Date())
|
||||
gtag('config', ga4MeasurementId)
|
||||
}
|
||||
}, [ga4MeasurementId, gtmContainerId])
|
||||
}, [ready, ga4MeasurementId, gtmContainerId])
|
||||
|
||||
// --- Non-Google: load each when its consent category is granted ---
|
||||
// The loaders are idempotent, so re-running on state changes is safe; a tag
|
||||
// loads the first time its category flips to true and never doubles up.
|
||||
// --- Non-Google: each when `ready` AND its consent category is granted ---
|
||||
// Loaders are idempotent, so re-running on state changes is safe; a tag loads
|
||||
// the first time both conditions hold and never doubles up.
|
||||
useEffect(() => {
|
||||
if (!ready) {return}
|
||||
if (state.marketing) {
|
||||
if (metaPixelId) {loadMetaPixel(metaPixelId)}
|
||||
if (linkedInPartnerId) {loadLinkedIn(linkedInPartnerId)}
|
||||
@@ -89,6 +162,7 @@ export function Analytics(props: AnalyticsConfig) {
|
||||
}
|
||||
if (state.analytics && clarityProjectId) {loadClarity(clarityProjectId)}
|
||||
}, [
|
||||
ready,
|
||||
state.marketing,
|
||||
state.analytics,
|
||||
metaPixelId,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
'use client'
|
||||
export { Analytics } from './Analytics.js'
|
||||
export type { AnalyticsProps } from './Analytics.js'
|
||||
// Low-level pixel loaders — exported for manual conversion events if a project
|
||||
// needs them (Analytics loads them automatically, consent-gated).
|
||||
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js'
|
||||
|
||||
Reference in New Issue
Block a user