Skip to content

Latest commit

 

History

History
70 lines (54 loc) · 2 KB

next-script-for-ga.md

File metadata and controls

70 lines (54 loc) · 2 KB

Next Script for Google Analytics

Why This Error Occurred

An inline script was used for Google analytics which might impact your webpage's performance.

Possible Ways to Fix It

Script component (experimental)

Use the Script component with the right loading strategy to defer loading of the script until necessary.

import Script from 'next/experimental-script'

const Home = () => {
  return (
    <div class="container">
      <Script>
        {`
          (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)
              })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
              
              ga('create', 'UA-XXXXX-Y', 'auto');
              ga('send', 'pageview');
          })
        `}
      </Script>
    </div>
  )
}

export default Home

If you are using the alternative async variant:

import Script from 'next/experimental-script'

const Home = () => {
  return (
    <div class="container">
      <Script>
        {`
          window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
          ga('create', 'UA-XXXXX-Y', 'auto');
          ga('send', 'pageview');
          })
        `}
      </Script>
      <Script
        src="https://www.google-analytics.com/analytics.js"
        strategy="lazyOnload"
      ></Script>
    </div>
  )
}

export default Home

Note: This is still an experimental feature and needs to be enabled via the experimental.scriptLoader flag in next.config.js.

Useful Links