Caching Google Analytics

This site uses cookies. By continuing to browse this site, you are agreeing to our Cookie Policy.

  • Google has developed a useful tool you can optimize your websites with. This tool (PageSpeed Insights) Google Insights scans your website and gives you tips on how to improve page speed performance and Google rank. One of the things Google Insights scans for is the caching of resources. With resources I mean images, javascript and stylesheets. However Google also warns you about their own resources. They have a cache expiry of 30 minutes. This can potentially slow you site down.

    What can you do about this? After I looked into the code and Googled some things, I found out that you can get the code of their website and use it on your own site. Google Analytics uses analytics.js and you can find it here: google-analytics.com/analytics.js. You probably already added the following code to your website, but you have to change a few things:

    Source Code

    1. <script>
    2. (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    3. (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    4. m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    5. })(window,document,'script','[LINK TO YOUR ANALYTICS.JS]','ga');
    6. ga('create', '[YOUR CODE]', 'auto');
    7. ga('send', 'pageview');
    8. </script>


    Change the info between [BRACKETS] to your own.

    Now Google Analytics should still work. Next we'll have to make sure the script will update itself. You don't want people to cache for just half an hour, but something like a day. This is more reasonable in my opinion. We'll have to make a script + cronjob to update analytics.js every day. You'll optimize speed performance, but also keep up-to-date.

    This simple script should update analytics.js. Upload this outside of your public_html.

    PHP Source Code

    1. <?php
    2. $location = 'analytics.js' //Location of your JS file
    3. $analytics = file_get_contents('http://www.google-analytics.com/analytics.js');
    4. file_put_contents($analytics, $locatie);
    5. ?>


    Let me now if you need help. I have been using it for a while now and it works great!
    Met vriendelijke groet,

    Victor
    Beheerder ICTscripters

    643 times read

Comments 0