The Google devguide says the following:
To install the global tracking snippet, copy the following code and paste it immediately after the tag on every page of your site. Replace GA_TRACKING_ID with the tracking ID of the Google Analytics property to which you want to send data. You need only one global snippet per page.
https://developers.google.com/analytics/devguides/collection/gtagjs/
In an ideal world where you can edit the HTML as you want this is not a problem of course. As soon as you are writing plugins for usage in many sites it IS a problem. WordPress for example. Each Theme has to support the wp_head()
function to hook in. The output is before the closing head tag of each theme. As well as wp_footer()
which is called right before the closing body tag.
Now I wonder if it may harm SEO if I put Google Analytics into the header just before the closing tag.
My code is like this:
function add_google_gtag_analytics() {
// tagmanager
wp_register_script(
'google-gtag', // handle name referred to in the "wp_enqueue_script" call below
'https://www.googletagmanager.com/gtag/js?id=' . $tracking_id, // location of your file
false, // no dependencies
'1.0', // version number
true // if true, the script is placed before the end tag
);
// google analytics
wp_register_script(
'google-analytics', // handle name referred to in the "wp_enqueue_script" call below
plugins_url('js/google_analytics', __FILE__), // location of your file
['google-gtag'], // no dependencies
'1.0', // version number
true // if true, the script is placed before the end tag
);
// pass analytics id variable
wp_localize_script('google-analytics', 'CIS_ANALYTICS_TRACKING_ID', $tracking_id);
// Enqueue the registered script file
wp_enqueue_script('google-gtag');
wp_enqueue_script('google-analytics');
}
add_action('wp_enqueue_scripts', 'add_google_analytics', 100);
// ensure tag manager async
add_filter('script_loader_tag', 'cis_gtag_async', 10, 3);
function cis_gtag_async($tag, $handle, $src) {
if ($handle !== 'google-gtag') {
return $tag;
}
return "<script src='$src' async></script>";
}
The priority of 100 makes sure that it is the last script to be embedded in the header (see add_action() in WP docs). The result of the above code is basically:
<head>
<!-- lots of meta, scripts and style tags -->
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_TRACKING_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'GA_TRACKING_ID');
</script>
</head>
<body>
Does anybody know if this can harm tracking or SEO?