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(analytics): defer google analytics script #22806

Merged
merged 4 commits into from
Apr 23, 2020
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
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