Learn about Centmin Mod LEMP Stack today
Register Now

WebPerf Local Analytics – Fix “Leverage Browser Caching” Warning

Discussion in 'All Internet & Web Performance News' started by eva2000, Jun 10, 2016.

  1. eva2000

    eva2000 Administrator Staff Member

    55,816
    12,275
    113
    May 24, 2014
    Brisbane, Australia
    Ratings:
    +18,861
    Local Time:
    5:28 PM
    Nginx 1.27.x
    MariaDB 10.x/11.4+
    At some point in time when you are running speed tests with your website you will most likely encounter the all popular “leverage browser caching” warning in Google PageSpeed Insights. And we are referring to the one originating from Google’s analytics.js script. In this post today we are going to show you a couple options on how to easily setup local analytics to fix this warning. Depending upon your environment you might also see a slight performance improvement. We have also included a new way to more easily do this for those of you running WordPress.


    Google Analytics “Leverage Browser Caching” Warning


    As we covered in our other post on Google PageSpeed insights, a lot of people try and strive for that 100/100 score on Google PageSpeed Insights. Some do it because they are trying to speed up their site and others because a client is demanding they meet this metric (yes, this happens more than you think). It is important to take some time though and think about why we are trying to achieve that 100/100 score. Don’t think of it solely from a metrics point of view. The whole reason Google developed PageSpeed Insights was as a guideline on best web performance practices to provide recommendations to optimize your site. And by following the guidelines hopefully you will achieve a faster website. We don’t recommend obsessing over this metric.

    There are some warnings which can be a little frustrating, such as with the “Leverage browser caching” warning, because it is coming from Google’s own analytics.js script. Kind of ironic that their own optimization tools gives us a warning. It is a valid warning as they set the cache time on their script very low. Most likely this is in case they push out any updates, they want everyone to get the new script within a short amount of time.

    As you can see in the screenshot below on our test site, we got everything to 99/100, except for that “Leverage browser caching” warning from Google Analytics script. To fix this we host their script locally.

    [​IMG]

    There are other reasons why you might want to host local analytics besides fixing the PageSpeed Insights error. Don’t expect to see huge performance gains by doing this, but you might see a little.

    • By hosting locally you can ensure that their large script loads from your web server, or CDN, instead of having to reach out to Google.
    • Instead of 2 HTTP requests to Google, you now only have 1.
    • When you host locally, you now have full control over caching, expires headers, cache-control, etc.
    • Take advantage of your single HTTP/2 connection
    Linking Normally to Google Analytics


    We ran some tests with WebPageTest. When we linked to Google’s analytics.js it seemed to always result in a larger DNS lookup time the first time around, as opposed to when we hosted locally.

    Total Load Time: 2.100s
    Fully loaded: 2.157s


    [​IMG]

    Local Analytics


    We ran some tests with WebPageTest. When we hosted the analytics script locally, obviously it loads super fast from our same HTTP/2 single connection on our CDN. It then has to do the DNS lookup on the final HTTP request to Google, but the DNS lookup was always a lot less. Doing it this way also results in what we like to call, “a nicer looking waterfall.”

    Total Load Time: 2.011s
    Fully loaded: 2.053s


    [​IMG]

    Again because this test is so small, your results might vary. Always do your own testing as each environment is different. But in our testing we did see a slight improvement to performance.


    How to Fix GA “Leverage Browser Caching” Warning


    Normally the way we would fix a “Leverage Browser Caching” warning would be to simply add expires headers. However, since this is a 3rd party script hosted on Google’s servers we have no control over the headers. So a solution that does work is to grab a copy of Google’s analytics.js script, host it locally, and sync it periodically to ensure you are using the latest version. Again, please be aware that this is not officially supported by Google. Follow the steps below.

    Credits for some of the code and scripts below go to Daan van den Bergh, Matthew Horne, and Jørgen Nicolaisen.

    Step 1


    The very first thing you need to do is grab a copy of the contents of Google’s Analytics script here: google-analytics.com/analytics.js. We are using Universal Analytics. Create a new file, in our example we call ours local-ga.js, and paste the contents of Google’s script into it.

    [​IMG]

    Step 2


    Upload the local-ga.js file to your web server where it is accessible. Note: Permissions on this file need to be writable for everything to work correctly.

    [​IMG]

    Step 3


    Next, you need to update the Google Analytics tracking code on your website. Again, we are using the Universal tracking code. In our example below, you can see we have updated ours to point to our local-ga.js file, and or the copy that also resides on our CDN.
    Code (Text):
    <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','[B]https://cdn.yourdomain.com/local-ga.js[/B]','ga');
    
    ga('create', 'UA-xxxxxxx-x', 'auto');
    ga('send', 'pageview');
    </script>
    

    That should now be working on your site. A quick way to test it is to launch your site it incognito mode and view real-time analytics. Ensure that tracking is working properly before proceeding.

    Step 4


    The next step is to setup a script so that your local script is periodically updated with Google’s hosted version. Otherwise they might push out an update/change and the tracking of your traffic could stop reporting correctly. In our example we name ours ga-update.php.
    Code (Text):
    <?
    // script to update local version of Google analytics script
    
    // Remote file to download
    $remoteFile = 'https://www.google-analytics.com/analytics.js[URL='https://www.google-analytics.com/analytics.js';']';[/URL]
    $localfile = 'ENTER YOUR ABSOLUTE PATH TO THE FILE HERE';
    //For Cpanel it will be /home/USERNAME/public_html/local-ga.js
    
    // Connection time out
    $connTimeout = 10;
    $url = parse_url($remoteFile);
    $host = $url['host'];
    $path = isset($url['path']) ? $url['path'] : '/';
    
    if (isset($url['query'])) {
    $path .= '?' . $url['query'];
    }
    
    $port = isset($url['port']) ? $url['port'] : '80';
    $fp = @fsockopen($host, '80', $errno, $errstr, $connTimeout );
    if(!$fp){
    // On connection failure return the cached file (if it exist)
    if(file_exists($localfile)){
    readfile($localfile);
    }
    } else {
    // Send the header information
    $header = "GET $path HTTP/1.0\r\n";
    $header .= "Host: $host\r\n";
    $header .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6\r\n";
    $header .= "Accept: */*\r\n";
    $header .= "Accept-Language: en-us,en;q=0.5\r\n";
    $header .= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
    $header .= "Keep-Alive: 300\r\n";
    $header .= "Connection: keep-alive\r\n";
    $header .= "Referer: http://$host\r\n\r\n";
    fputs($fp, $header);
    $response = '';
    
    // Get the response from the remote server
    while($line = fread($fp, 4096)){
    $response .= $line;
    }
    
    // Close the connection
    fclose( $fp );
    
    // Remove the headers
    $pos = strpos($response, "\r\n\r\n");
    $response = substr($response, $pos + 4);
    
    // Return the processed response
    echo $response;
    
    // Save the response to the local file
    if(!file_exists($localfile)){
    // Try to create the file, if doesn't exist
    fopen($localfile, 'w');
    }
    
    if(is_writable($localfile)) {
    if($fp = fopen($localfile, 'w')){
    fwrite($fp, $response);
    fclose($fp);
    }
    }
    }
    ?>
    

    Step 5


    The last step is that you will need to setup a Cron job that runs the script above periodically. This will update your local-ga.js file with the latest version from Google. If your web host doesn’t let you setup Cron jobs, you can always use an external service like SetCronJob.

    Fix GA “Leverage Browser Caching” Warning in WordPress


    If you are running WordPress, there is now a great free little plugin called Host Analytics.js Locally that can do the above for you! It was created by Daan van den Bergh and enables you to host your Google Analytics javascript-file (analytics.js) locally and keep it updated using wp_cron(). To further optimize your sites’ usage of Google Analytics, it allows you to optionally set Adjusted Bounce Rate and decided whether to load the Analytics Tracking-code in the header or footer.

    [​IMG]

    Step 1


    Download Host Analytics.js Locally from the WordPress repository or do a search from your WordPress dashboard for “host analytics.”

    [​IMG]

    Step 2


    After you have installed and activated it, go into the plugin settings and enter in your Google Analytics Tracking ID and position for your tracking code. You can also enter in your adjusted bounce rate in seconds.

    [​IMG]

    And the great news is that it works perfectly with KeyCDN’s WordPress CDN enabler plugin. So the plugin above will sync across Google’s analytics script and then our plugin will copy it to your CDN. Again remember to test to ensure it is working properly. A quick way to test it is to launch your site it incognito mode and view real-time analytics.

    And now there should be no more “leverage browser caching” warning, at least as far as Google Analytics is concerned.

    [​IMG]

    Summary


    As you can see there are some great alternatives out there for local analytics if you are trying to fix the Google Analytics “leverage browser caching” warning in PageSpeed Insights. You might even see a small performance improvement. Have you experimented with hosting Google Analytics locally? If so we would love to hear your thoughts below.

    Related Articles


    The post Local Analytics – Fix “Leverage Browser Caching” Warning appeared first on KeyCDN Blog.

    Continue reading...
     
    Last edited: Jun 10, 2016
  2. rdan

    rdan Well-Known Member

    5,451
    1,412
    113
    May 25, 2014
    Ratings:
    +2,206
    Local Time:
    3:28 PM
    Mainline
    10.2
    Anybody implemented this thing already? :)
     
  3. eva2000

    eva2000 Administrator Staff Member

    55,816
    12,275
    113
    May 24, 2014
    Brisbane, Australia
    Ratings:
    +18,861
    Local Time:
    5:28 PM
    Nginx 1.27.x
    MariaDB 10.x/11.4+
    0.1s isn't much savings for the work involved. You could save 150kb in image size off a page and have a bigger impact. PageSpeed insight score isn't everything :)