diff --git a/packages/gatsby-plugin-google-analytics/README.md b/packages/gatsby-plugin-google-analytics/README.md index 481f6b87b79a3..204cd5b914d24 100644 --- a/packages/gatsby-plugin-google-analytics/README.md +++ b/packages/gatsby-plugin-google-analytics/README.md @@ -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, diff --git a/packages/gatsby-plugin-google-analytics/src/__tests__/gatsby-ssr.js b/packages/gatsby-plugin-google-analytics/src/__tests__/gatsby-ssr.js index 2f772b897f532..e97a649980078 100644 --- a/packages/gatsby-plugin-google-analytics/src/__tests__/gatsby-ssr.js +++ b/packages/gatsby-plugin-google-analytics/src/__tests__/gatsby-ssr.js @@ -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;`) + }) }) }) }) diff --git a/packages/gatsby-plugin-google-analytics/src/gatsby-ssr.js b/packages/gatsby-plugin-google-analytics/src/gatsby-ssr.js index 2ef6737009e88..3524f7b6aa80f 100644 --- a/packages/gatsby-plugin-google-analytics/src/gatsby-ssr.js +++ b/packages/gatsby-plugin-google-analytics/src/gatsby-ssr.js @@ -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") {