2

I have a JavaScript file which is loaded up at the end of my HTML page.

Rather than adding the script code for asynchronous tracking for Google in yet another script I would rather combine the two scripts together.

So instead of this:

    <html>
        ...

        <script src="myScript.js">

        <!-- google analytics -->
        <script type="text/javascript">

            var _gaq = _gaq || [];
            _gaq.push(['_setAccount', 'UA-XXXXX-X']);
            _gaq.push(['_trackPageview']);

            (function() {
                var ga = document.createElement('script');
                    ga.type = 'text/javascript';
                    ga.async = true;
                ga.src =
                  ('https:' == document.location.protocol ?
                      'https://ssl' :
                      'http://www') + '.google-analytics.com/ga.js';
                (document.getElementsByTagName('head')[0] ||
                 document.getElementsByTagName('body')[0]).appendChild(ga);
            })();
        </script>
    </html>

I would have that bit of code in the second script tag at the end of my 'myScript.js'.

I have not found one place in google documentation where it suggests to combine the script with yours.

How can I solve this problem?

2 Answers 2

2

The whole point of the asynchronous Google Analytics snippet is to start gathering data as soon as possible — even before other JavaScript files are finished loading. Putting the code at the end of your scripts.js file pretty much defeats that purpose.

If you want to put it in a separate .js file so the snippet code can be cached client-side, that’s great! But make sure to load it before your other scripts:

<script src="analytics-snippet.js"></script>
<script src="other-scripts.js"></script>

Of course, this is one additional HTTP request, but let’s optimize for the case where every visitor browses more than one page on your site.

Also, you can replace:

(document.getElementsByTagName('head')[0] ||
             document.getElementsByTagName('body')[0]).appendChild(ga);

With:

(document.head || document.getElementsByTagName('head')[0] || document.body).appendChild(ga);
1

Combining the scripts works absolutely fine (in fact, I have done it on one of my sites). As long as the order of the Google code is still the same, then it will work perfectly.

2

Not the answer you're looking for? Browse other questions tagged or ask your own question.