Skip to content

Commit fb15bab

Browse files
Slashgeargatsbybot
and
gatsbybot
authored
feat(analytics): defer google analytics script (#22806)
* feat(analytics): defer google analytics script * add defer as an option - add test - update doc * use async xor defer Co-authored-by: gatsbybot <[email protected]>
1 parent e8b026d commit fb15bab

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

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

+2
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ module.exports = {
3333
experimentId: "YOUR_GOOGLE_EXPERIMENT_ID",
3434
// Set Variation ID. 0 for original 1,2,3....
3535
variationId: "YOUR_GOOGLE_OPTIMIZE_VARIATION_ID",
36+
// Defers execution of google analytics script after page load
37+
defer: false,
3638
// Any additional optional fields
3739
sampleRate: 5,
3840
siteSpeedSampleRate: 10,

packages/gatsby-plugin-google-analytics/src/__tests__/gatsby-ssr.js

+18
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,24 @@ describe(`gatsby-plugin-google-analytics`, () => {
172172
const result = JSON.stringify(setPostBodyComponents.mock.calls[0][0])
173173
expect(result).not.toContain(`allowAdFeatures`)
174174
})
175+
176+
it(`should defer script after the site render when set`, () => {
177+
const { setPostBodyComponents } = setup({
178+
defer: true,
179+
})
180+
181+
const result = JSON.stringify(setPostBodyComponents.mock.calls[0][0])
182+
expect(result).toContain(`defer=1;`)
183+
expect(result).not.toContain(`async=1;`)
184+
})
185+
186+
it(`should not defer script after the site render`, () => {
187+
const { setPostBodyComponents } = setup({})
188+
189+
const result = JSON.stringify(setPostBodyComponents.mock.calls[0][0])
190+
expect(result).not.toContain(`defer=1;`)
191+
expect(result).toContain(`async=1;`)
192+
})
175193
})
176194
})
177195
})

packages/gatsby-plugin-google-analytics/src/gatsby-ssr.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,9 @@ export const onRenderBody = (
8383
}) {
8484
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
8585
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
86-
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
86+
m=s.getElementsByTagName(o)[0];${
87+
pluginOptions.defer ? `a.defer=1;` : `a.async=1;`
88+
}a.src=g;m.parentNode.insertBefore(a,m)
8789
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
8890
}
8991
if (typeof ga === "function") {

0 commit comments

Comments
 (0)