Skip to content

Commit c132f2d

Browse files
authored
feat(gatsby-plugin-google-gtag): Add delayOnRouteUpdate option (#37017)
Fixes #15504
1 parent 3032a1b commit c132f2d

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

packages/gatsby-plugin-google-gtag/README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ module.exports = {
5050
exclude: ["/preview/**", "/do-not-track/me/too/"],
5151
// Defaults to https://www.googletagmanager.com
5252
origin: "YOUR_SELF_HOSTED_ORIGIN",
53+
// Delays processing pageview events on route update (in milliseconds)
54+
delayOnRouteUpdate: 0,
5355
},
5456
},
5557
},
@@ -137,3 +139,7 @@ If you enable this optional option, Google Global Site Tag will not be loaded at
137139
## The "pluginConfig.exclude" option
138140

139141
If you need to exclude any path from the tracking system, you can add it (one or more) to this optional array as glob expressions.
142+
143+
## The "pluginConfig.delayOnRouteUpdate" option
144+
145+
If you need to delay processing pageview events on route update (e.g. to wait for page transitions with [`gatsby-plugin-transition-link`](https://www.gatsbyjs.com/plugins/gatsby-plugin-transition-link/)), then this option adds a delay before generating the pageview event.

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

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1-
exports.onRouteUpdate = ({ location }) => {
1+
exports.onRouteUpdate = ({ location }, pluginOptions = {}) => {
22
if (process.env.NODE_ENV !== `production` || typeof gtag !== `function`) {
33
return null
44
}
55

6+
const pluginConfig = pluginOptions.pluginConfig || {}
7+
68
const pathIsExcluded =
79
location &&
810
typeof window.excludeGtagPaths !== `undefined` &&
@@ -18,13 +20,15 @@ exports.onRouteUpdate = ({ location }) => {
1820
window.gtag(`event`, `page_view`, { page_path: pagePath })
1921
}
2022

23+
const { delayOnRouteUpdate = 0 } = pluginConfig
24+
2125
if (`requestAnimationFrame` in window) {
2226
requestAnimationFrame(() => {
23-
requestAnimationFrame(sendPageView)
27+
requestAnimationFrame(() => setTimeout(sendPageView, delayOnRouteUpdate))
2428
})
2529
} else {
26-
// simulate 2 rAF calls
27-
setTimeout(sendPageView, 32)
30+
// Delay by 32ms to simulate 2 requestOnAnimationFrame calls
31+
setTimeout(sendPageView, 32 + delayOnRouteUpdate)
2832
}
2933

3034
return null

0 commit comments

Comments
 (0)