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

前端 未结 20 1528
無奈伤痛
無奈伤痛 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.

    0 讨论(0)
  • 2020-11-29 15:22

    Well, if Google is cheating on you, you can cheat Google back:

    This is the user-agent for pageSpeed:

    “Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.8 (KHTML, like Gecko; Google Page Speed Insights) Chrome/19.0.1084.36 Safari/536.8”
    

    You can insert a conditional to avoid serving the analytics script to PageSpeed:

    <?php if (!isset($_SERVER['HTTP_USER_AGENT']) || stripos($_SERVER['HTTP_USER_AGENT'], 'Speed Insights') === false): ?>
    // your analytics code here
    <?php endif; ?>
    

    Obviously, it won't make any real improvement, but if your only concern is getting a 100/100 score this will do it.

    0 讨论(0)
  • 2020-11-29 15:22

    PHP

    Add this in your HTML or PHP code:

    <?php if (!isset($_SERVER['HTTP_USER_AGENT']) || stripos($_SERVER['HTTP_USER_AGENT'], 'Speed Insights') === false): ?>
      <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-PUT YOUR GOOGLE ANALYTICS ID HERE', 'auto');
        ga('send', 'pageview');
      </script>
    <?php endif; ?>
    

    JavaScript

    This works fine with JavaScript:

      <script>
      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-<PUT YOUR GOOGLE ANALYTICS ID HERE>', 'auto');
        ga('send', 'pageview');
      }
      </script>
    

    NiloVelez already said: Obviously, it won't make any real improvement, but if your only concern is getting a 100/100 score this will do it.

    0 讨论(0)
  • 2020-11-29 15:23

    This may do the trick :)

    <script>
      $.ajax({
      type: "GET",
      url: "https://www.google-analytics.com/analytics.js",
      success: function(){},
      dataType: "script",
      cache: true
      });
    </script>
    
    0 讨论(0)
  • 2020-11-29 15:23

    You can set up a cloudfront distribution that has www.google-analytics.com as its origin server and set a longer expiry header in the cloudfront distribution settings. Then modify that domain in the Google snippet. This prevents the load on your own server and the need to keep updating the file in a cron job.

    This is setup & forget. So you may want to add a billing alert to cloudfront in case someone "copies" your snippet and steals your bandwidth ;-)

    Edit: I tried it and it's not that easy, Cloudfront passes through the Cache-Control header with no easy way to remove it

    0 讨论(0)
  • 2020-11-29 15:24

    varvy.com (100/100 Google page speed insight) loads google analitycs code only if user make a scroll of the page:

    var fired = false;
    
    window.addEventListener("scroll", function(){
        if ((document.documentElement.scrollTop != 0 && fired === false) || (document.body.scrollTop != 0 && fired === false)) {
    
            (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','//www.google-analytics.com/analytics.js','ga');
    
            ga('create', 'UA-XXXXXXXX-X', 'auto');
            ga('send', 'pageview');
    
            fired = true;
        }
    }, true);
    
    0 讨论(0)
提交回复
热议问题