Search code examples
javascripthtmlgoogle-tag-managerhtml5boilerplate

How high in the <head> section can you safely put the Google Tag Manager code?


Google Tag Manager instructs developers to:

Paste this code [THE TRACKING CODE] as high in the <head> of the page as possible:

<!-- Google Tag Manager --> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-XXXXXXX');</script> <!-- End Google Tag Manager -->

My question is, how high can that code be properly placed? Properly meaning, able to function on >95% of browsers without issues/warnings/errors, and/or according to HTML best practices.

Can it go right after the opening <head> tag? Does it really matter as long as it is in the <head> section somewhere?

For reference/example, below is the HTML boilerplate. What's the best spot for the tracking code in the boilerplate?

<!doctype html>
<html class="no-js" lang="">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="manifest" href="site.webmanifest">
        <link rel="apple-touch-icon" href="icon.png">
        <!-- Place favicon.ico in the root directory -->

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">
    </head>
    <body>
        <!--[if lte IE 9]>
            <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="https://browsehappy.com/">upgrade your browser</a> to improve your experience and security.</p>
        <![endif]-->

        <!-- Add your site or application content here -->
        <p>Hello world! This is HTML5 Boilerplate.</p>
        <script src="js/vendor/modernizr-{{MODERNIZR_VERSION}}.min.js"></script>
        <script src="https://code.jquery.com/jquery-{{JQUERY_VERSION}}.min.js" integrity="{{JQUERY_SRI_HASH}}" crossorigin="anonymous"></script>
        <script>window.jQuery || document.write('<script src="js/vendor/jquery-{{JQUERY_VERSION}}.min.js"><\/script>')</script>
        <script src="js/plugins.js"></script>
        <script src="js/main.js"></script>

        <!-- Google Analytics: change UA-XXXXX-Y to be your site's ID. -->
        <script>
            window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;
            ga('create','UA-XXXXX-Y','auto');ga('send','pageview')
        </script>
        <script src="https://www.google-analytics.com/analytics.js" async defer></script>
    </body>
</html>

Solution

  • The reason why Google recommends putting it as high up as possible is primarily to improve accuracy in tracking. The higher up in the page the snippet is, the faster it is loaded. Placing the snippet lower in your page, can potentially miss tracking users who left your page before the code was loaded. It can also cause to mistakenly report a site visitor that navigated away from your homepage before the code was loaded as a direct visitor to the page the user navigated to.

    It is also important with Google’s A/B testing tool, Optimize. Having the snippet load faster ensures that Optimize will load the correct version of the page as soon as possible.

    However, there are other factors you might want to consider, as discussed here: What are best practices to order elements in <head>?. For example:

    ...For this reason, HTML5 specifies that any meta tag which is used to specify the character set (either <meta http-equiv="Content-type" content="text/html; charset=..."> or simply <meta charset=...>) must be within the first 1024 bytes of the file in order to take effect. So, if you are going to include character encoding information within your document, you should put the tag early in the file, possibly even before the <title> element.

    So although you can put your tracking code snippet immediately following the opening head tag, you might want to consider putting it after the most important meta tags. Those tags generally don't take long to load, and won't hold off your tracking code much.

    But yes, it does matter where in the head you put your tracking code for the reasons mentioned above. So if you'll be loading many scripts, stylesheets, etc., then put your tag manager code higher up rather than just dropping it at the end.

    <!doctype html>
    <html class="no-js" lang="">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    
        <!-- Tracking Code -->
    
        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">