In this video, I’ll show you how to use Google Analytics without it affecting your PageSpeed score.
The default installation code that Google gives you to install Analytics on your website can slow your pagespeed score by 11 points or more.
Using this method, by only loading analytics when a user scrolls or moves their mouse, you’ll still capture everything in analytics without getting hurt on your pagespeed report.
Disclaimer: If bounce rate is super important to you, please don’t use this code. If a user does not scroll or move their mouse, their visit will not be captured. To me, such a visit is just about meaningless. However, just about everyone will at least move their mouse or scroll, so bounce rates won’t be affected that much. Everything else is as normal.
On to the code! You will need your default analytics install code, and you’ll need to copy the id from the code. This ID starts with G- and can be find in the gtag(‘config’, ) line.
*Replace “YOURGOOGLEIDHERE” in the following code.*
<script>
/**
* Scottsweb.dev
* Load google analytics after a user interaction (scroll or mousemovement).
* This method may not gather all analytics such as bounces, but it will remove
* google analytics from the pagespeed score
*/
let analytics_loaded = false;
let analytics_script_id = 'YOURGOOGLEIDHERE';
function swd_load_analytics() {
if (!analytics_loaded) {
let analytics_script = document.createElement('script');
analytics_script.src = 'https://www.googletagmanager.com/gtag/js?id=' + analytics_script_id;
analytics_script.onload = function() {
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', analytics_script_id);
};
document.head.appendChild(analytics_script);
analytics_loaded = true;
}
}
document.addEventListener('DOMContentLoaded', function() {
window.addEventListener('scroll', swd_load_analytics);
window.addEventListener('mousemove', swd_load_analytics);
});
</script>
Related: More PageSpeed
Load Youtube Videos without affecting Google PageSpeed scores.