Skip to content

Commit 42f509e

Browse files
fix(google-analytics): fix pageview timing issue by delaying it (#10917)
There is still a problem with title and path not being correct while navigating across a page. As referenced in: #9139 Solution made in: #2478 and #3362 For some reason the previous solution is being overwritten Co-authored-by: Ward Peeters <ward@coding-tech.com>
1 parent 2fc85d7 commit 42f509e

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

packages/gatsby-plugin-google-analytics/src/gatsby-browser.js

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,27 @@ exports.onRouteUpdate = function({ location }) {
88
) {
99
return
1010
}
11-
window.ga(
12-
`set`,
13-
`page`,
14-
location ? location.pathname + location.search + location.hash : undefined
15-
)
16-
window.ga(`send`, `pageview`)
11+
12+
// wrap inside a timeout to make sure react-helmet is done with it's changes (https://github.com/gatsbyjs/gatsby/issues/9139)
13+
// reactHelmet is using requestAnimationFrame so we should use it too: https://github.com/nfl/react-helmet/blob/5.2.0/src/HelmetUtils.js#L296-L299
14+
const sendPageView = () => {
15+
window.ga(
16+
`set`,
17+
`page`,
18+
location
19+
? location.pathname + location.search + location.hash
20+
: undefined
21+
)
22+
window.ga(`send`, `pageview`)
23+
}
24+
25+
if (`requestAnimationFrame` in window) {
26+
requestAnimationFrame(() => {
27+
requestAnimationFrame(sendPageView)
28+
})
29+
} else {
30+
// simulate 2 rAF calls
31+
setTimeout(sendPageView, 32)
32+
}
1733
}
1834
}

0 commit comments

Comments
 (0)