Thursday, 6 July 2023

Don't display GA4 code to Google Lighthouse and Google PageSpeed

Google Analytics code removes one score from achieving a 100/100 score on PageSpeed Insights.

The solution with the Universal Analytics (UA) was to not show it to the google crawlers via:

if(navigator.userAgent.indexOf("Speed Insights") == -1 && navigator.userAgent.indexOf("Chrome-Lighthouse") == -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');
}

Worked fine.

But as of today, UA is being deprecated and everyone needs to upgrade to Google Analytics 4 (GA4).

How can we use this code for GA4? So we don't display it to the appropriate Google crawlers.



from Don't display GA4 code to Google Lighthouse and Google PageSpeed

No comments:

Post a Comment