Skip to content

Commit

Permalink
feat: add delayOnRouteUpdate option to gatsby-plugin-google-gtag
Browse files Browse the repository at this point in the history
  • Loading branch information
Simon-Tang committed Nov 11, 2022
1 parent 3a4d333 commit 2de4641
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
6 changes: 6 additions & 0 deletions packages/gatsby-plugin-google-gtag/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ module.exports = {
exclude: ["/preview/**", "/do-not-track/me/too/"],
// Defaults to https://www.googletagmanager.com
origin: "YOUR_SELF_HOSTED_ORIGIN",
// Delays processing pageview events on route update (in milliseconds)
delayOnRouteUpdate: 0,
},
},
},
Expand Down Expand Up @@ -137,3 +139,7 @@ If you enable this optional option, Google Global Site Tag will not be loaded at
## The "pluginConfig.exclude" option

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.

## The "pluginConfig.delayOnRouteUpdate" option

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.
10 changes: 6 additions & 4 deletions packages/gatsby-plugin-google-gtag/src/gatsby-browser.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
exports.onRouteUpdate = ({ location }) => {
exports.onRouteUpdate = ({ location }, pluginOptions = {}) => {
if (process.env.NODE_ENV !== `production` || typeof gtag !== `function`) {
return null
}
Expand All @@ -18,13 +18,15 @@ exports.onRouteUpdate = ({ location }) => {
window.gtag(`event`, `page_view`, { page_path: pagePath })
}

const { delayOnRouteUpdate = 0 } = pluginOptions

if (`requestAnimationFrame` in window) {
requestAnimationFrame(() => {
requestAnimationFrame(sendPageView)
requestAnimationFrame(() => setTimeout(sendPageView, delayOnRouteUpdate))
})
} else {
// simulate 2 rAF calls
setTimeout(sendPageView, 32)
// Delay by 32ms to simulate 2 requestOnAnimationFrame calls
setTimeout(sendPageView, 32 + delayOnRouteUpdate)
}

return null
Expand Down

0 comments on commit 2de4641

Please sign in to comment.