Skip to content

Commit

Permalink
feat(analytics): defer google analytics script (#22806)
Browse files Browse the repository at this point in the history
* feat(analytics): defer google analytics script

* add defer as an option

- add test
- update doc

* use async xor defer

Co-authored-by: gatsbybot <mathews.kyle+gatsbybot@gmail.com>
  • Loading branch information
Slashgear and gatsbybot authored Apr 23, 2020
1 parent e8b026d commit fb15bab
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
2 changes: 2 additions & 0 deletions packages/gatsby-plugin-google-analytics/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ module.exports = {
experimentId: "YOUR_GOOGLE_EXPERIMENT_ID",
// Set Variation ID. 0 for original 1,2,3....
variationId: "YOUR_GOOGLE_OPTIMIZE_VARIATION_ID",
// Defers execution of google analytics script after page load
defer: false,
// Any additional optional fields
sampleRate: 5,
siteSpeedSampleRate: 10,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,24 @@ describe(`gatsby-plugin-google-analytics`, () => {
const result = JSON.stringify(setPostBodyComponents.mock.calls[0][0])
expect(result).not.toContain(`allowAdFeatures`)
})

it(`should defer script after the site render when set`, () => {
const { setPostBodyComponents } = setup({
defer: true,
})

const result = JSON.stringify(setPostBodyComponents.mock.calls[0][0])
expect(result).toContain(`defer=1;`)
expect(result).not.toContain(`async=1;`)
})

it(`should not defer script after the site render`, () => {
const { setPostBodyComponents } = setup({})

const result = JSON.stringify(setPostBodyComponents.mock.calls[0][0])
expect(result).not.toContain(`defer=1;`)
expect(result).toContain(`async=1;`)
})
})
})
})
Expand Down
4 changes: 3 additions & 1 deletion packages/gatsby-plugin-google-analytics/src/gatsby-ssr.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,9 @@ export const onRenderBody = (
}) {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
m=s.getElementsByTagName(o)[0];${
pluginOptions.defer ? `a.defer=1;` : `a.async=1;`
}a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
}
if (typeof ga === "function") {
Expand Down

0 comments on commit fb15bab

Please sign in to comment.