DEV Community

Manuel Canga
Manuel Canga

Posted on

Google Analytics and WPO Analyzers

Translation of my old post: Google Analytics and WPO Analyzers

I’m increasingly seeing more criticism against Google PageSpeed Insights (and other WPO analyzers) because many find it contradictory that Google’s own flagship tracking service, Google Analytics, is flagged as an error. "But it’s from the same company!", you can hear them say.

Google Analytics, like other tracking services, consumes a lot of resources during a website's load. It’s commendable that a service like Google PageSpeed Insights flags this so you can optimize it. To me, it would lose credibility as a WPO tool if it didn’t. However, I understand that someone who doesn’t know about optimization might blame the tool instead. It reminds me of Aesop’s fable, The Fox and the Grapes.

One of the options used to optimize the Google Analytics script is to host it on your own server and set an expiration date so that browsers can cache it. This is something Google doesn’t recommend, which is understandable because it loses the ability to update its code whenever it wants. If you don't opt for this option, based on what Google says, you can easily overcome this by setting up a CRON job to download the Google Analytics script every few hours.

Another option (which is fully compatible with the previous one), and the one I use, is to load the Google Analytics script when someone scrolls on the page. This might seem detrimental because it might make you think it won’t track all users. However, in my opinion, it will give a more accurate metric:

  • First, it won’t track those who are quick to click a link on your site and, upon realizing their mistake, leave immediately.
  • It won’t track robots, spiders, or similar entities that present themselves as regular users (since they don’t send user-agent headers that identify their real nature).

Moreover, it’s an optimal option because the script will load once everything else is already loaded (so it won’t slow anything down) and transparently while the user is browsing your website.

Here’s the JavaScript code that makes this possible:

/**
 * Google Analytics and WPO Analyzers - WebPerf - Manuel Canga
 * From post: https://trasweb.net/snippets/google-analytics-and-wpo-analyzers
 */

var is_analytics_loaded = false;

load_googleAnalytics = function () {
    if (is_analytics_loaded) {
        return 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-xxxx', 'auto');
    ga('send', 'pageview');

    is_analytics_loaded = true;
};


window.addEventListener("scroll", function () {
    if (document.documentElement.scrollTop !== 0 || document.body.scrollTop !== 0) {
        load_googleAnalytics();
    }
}, true);
Enter fullscreen mode Exit fullscreen mode

From line 25 to line 29, we tell the browser that when the visitor scrolls (the scroll event is triggered, and the scroll bar position is no longer at the top), the load_googleAnalytics function should be executed. This function checks (lines 9 to 12) through a flag whether Analytics has already been loaded on the current page. If not, the tracking script is loaded (lines 13 to 19). Notice that in line 18, the Google Analytics ID is inserted. Finally, in line 21, the flag is activated to prevent the script from loading again.


If you liked it, don’t forget to share.

Top comments (0)