Floryne Pierson
← All posts

My analytics were broken for weeks and I didn't know

How a 2-second setTimeout on hundreds of pages made most of my traffic invisible to GA4 — and what I built to fix it properly.

I was looking at my GA4 data and something felt off. There were sessions full of custom events — readings completed, offers shown, buttons clicked — but no page_view, no session_start, no attribution. Around 80 sessions per day were arriving as (not set) in the Source/Medium report. They had engagement. They had no origin.

That's when I started digging.

The root cause

On hundreds of pages, gtag.js was loaded inside a window.addEventListener("load", () => setTimeout(..., 2000)) block. The intent was performance: don't block the page with analytics on first load.

The problem: on a slow 3G connection, window.load itself fires at 54 seconds. Add another 2 seconds and you're at 56 seconds before GA4 even initialises. Most users are long gone by then.

What actually happened: the custom events (tracked by a separate script that ran earlier) fired and reached the GA4 property just fine. But page_view, session_start and first_visit — which are produced by the GA4 configuration, not by custom code — never fired at all. So GA4 had engagement signals with no session context to attach them to.

The symptom: sessions with zero session_start, but dozens of page_view and user_engagement events. Every decision I made during that period was based on incomplete data.

The fix

The solution was to load gtag.js with a short, fixed delay instead of waiting for load:

// Before
window.addEventListener("load", () => {
  setTimeout(loadGtag, 2000);
});

// After
setTimeout(loadGtag, 300);

300ms is enough to avoid blocking the critical rendering path. It doesn't depend on the network state of the page. And critically, it's short enough that even fast users who bounce immediately still get a session_start recorded.

The 300ms delay also serves a second purpose: it gives the page time to render so that a bot-detection check I run against screen dimensions reads accurate values, rather than the emulated defaults that headless browsers set at load.

The hard part: applying it to hundreds of pages

Manually editing hundreds of HTML files wasn't an option. I wrote a Node script to do it automatically — but the first version had a bug that taught me something important.

The original approach used a single regex with [\s\S]*? to match the script block. On pages that had two loading blocks (one for gtag at 1500ms, one for GTM at 2000ms), the lazy quantifier jumped from the first block's opener to the second block's closing bracket. It merged both blocks into one and left orphaned syntax behind. JavaScript was invalid on 182 pages before I caught it.

The correct approach: parse the HTML structurally, block by block, counting open and close brackets instead of using a regex boundary. And before writing any modified block back to disk, compile it with new Function() — which parses without executing, so a syntax error throws before anything is saved.

// Validate before writing
try {
  new Function(modifiedScript);
} catch (e) {
  throw new Error(`Invalid JS on ${file}: ${e.message}`);
}

After the fix: every valid block rewritten, a small number skipped (already invalid in the source, unrelated to this change). Zero regressions.

What I learned

The obvious lesson is about loading order. But the more useful one is about control: a script that modifies files at scale needs a whitelist check, not just a rewrite. My final version of the script validates every output before it touches the filesystem, and runs a --check mode that confirms the invariant — "every page that configures GA4 also loads gtag.js without depending on load" — without making any changes.

If you're building a content site with hundreds or thousands of pages and third-party scripts, don't trust that everything is loading in the right order just because it works on your laptop on a fast connection. Measure it on slow 3G. You might find that your analytics have been lying to you for weeks.