views:

174

answers:

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?

+1  A: 

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.

You can take a look at mine here: clintonmontague.js - it is included at the very bottom of my page just before the tag :)

slightlymore
do you happen to know why this technique is never mentioned in any of google analytics documents ? it almost looks like they don't want to endorse it.
lorenzo 72
@lorenzo: I answered this in my post: http://stackoverflow.com/questions/2401308/2597908#2597908
Mathias Bynens
A: 

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);
Mathias Bynens