Skip to content

Commit 8e0b2cd

Browse files
justinegeffenclaude
andcommitted
fix: Wait for PostHog to load before setting up search tracking
Add polling mechanism to wait up to 5 seconds for window.posthog to be available before initializing search event listeners. This fixes the timing issue where PostHog loads asynchronously and isn't available when the module first runs. Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
1 parent 5940049 commit 8e0b2cd

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed

src/client-modules/posthog-search.js

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,22 @@
11
let debounceTimer;
22

3-
function trackSearch() {
4-
// Use the globally available PostHog instance (loaded via snippet)
5-
const ph = window.posthog;
3+
function waitForPostHog(callback, maxAttempts = 50, interval = 100) {
4+
let attempts = 0;
65

7-
if (!ph) {
8-
console.warn('PostHog not available. Search tracking will be disabled.');
9-
return;
10-
}
6+
const checkPostHog = () => {
7+
if (window.posthog) {
8+
callback(window.posthog);
9+
} else if (attempts < maxAttempts) {
10+
attempts++;
11+
setTimeout(checkPostHog, interval);
12+
}
13+
// Silently fail if PostHog doesn't load - it's optional analytics
14+
};
1115

16+
checkPostHog();
17+
}
18+
19+
function setupTracking(ph) {
1220
document.addEventListener('input', (e) => {
1321
const input = e.target.closest('.DocSearch-Input, [class*="searchBox"] input');
1422
if (!input) return;
@@ -34,5 +42,5 @@ function trackSearch() {
3442
}
3543

3644
if (typeof window !== 'undefined') {
37-
trackSearch();
45+
waitForPostHog(setupTracking);
3846
}

0 commit comments

Comments
 (0)