Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(gatsby-plugin-google-gtag): Add delayOnRouteUpdate option #37017

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.
12 changes: 8 additions & 4 deletions packages/gatsby-plugin-google-gtag/src/gatsby-browser.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
exports.onRouteUpdate = ({ location }) => {
exports.onRouteUpdate = ({ location }, pluginOptions = {}) => {
if (process.env.NODE_ENV !== `production` || typeof gtag !== `function`) {
return null
}

const pluginConfig = pluginOptions.pluginConfig || {}

const pathIsExcluded =
location &&
typeof window.excludeGtagPaths !== `undefined` &&
Expand All @@ -18,13 +20,15 @@ exports.onRouteUpdate = ({ location }) => {
window.gtag(`event`, `page_view`, { page_path: pagePath })
}

const { delayOnRouteUpdate = 0 } = pluginConfig

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