PageSpeed Insights 99/100 because of Google Analytics - How can I cache GA?

前端 未结 20 1674
無奈伤痛
無奈伤痛 2020-11-29 15:10

I\'m on a quest to reach 100/100 on PageSpeed and i\'m almost there. I\'m trying to find a good solution to cache Google Analytics.

Here is the message I get:

20条回答
  •  無奈伤痛
    2020-11-29 15:18

    Here is a really simple solution using JS, for basic GA tracking, which will also work for edge caches/proxies (this was converted from a comment):

    if(navigator.userAgent.indexOf("Speed Insights") == -1) {
      (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-XXXXXXXXX-X', 'auto');
      ga('send', 'pageview');
    }
    

    Note: This is the default GA script. You may have other ga() calls, and if so, you would need to always check the user agent before calling ga(), otherwise it may error out.

提交回复
热议问题