2

I was playing around with custom variables in Google Analytics and wasn't sure why the following actually works. Why does Google's tracking code get executed first, especially since it is at the bottom of the page?

Both scripts are in self-executing functions, so how does javascript determine which one to execute first?

 // top of the page
  <script type="text/javascript">
              $(function ()
              {
                    _gaq.push(['_setCustomVar', 1, 'Account', 'PartTime', 1]);
              });
        </script> 


// bottom of the page
        <script type="text/javascript">

            var _gaq = _gaq || [];
            _gaq.push(['_setAccount', 'UA-xxxxxxxxxx']);
            _gaq.push(['_setDomainName', '.xxxxxxxx.com']);
            _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';
                var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
            })();

         </script>  

1 Answer 1

5

The first one does execute first, and isn't in a self executing function.

It consists of a call to the $ function and has one argument: an anonymous function.

$ is a very badly named function. The name itself is meaningless and it has been adopted by half a dozen different libraries to do half a dozen different things.

In jQuery, if you pass a function to $ it runs that function when the ready event is triggered (but the end of the HTML document being parsed). This is probably what is happening here.

Sign up to request clarification or add additional context in comments.

2 Comments

I used firebug and put breakpoints in both functions and it goes to the google one first, then it goes into the one at the top. You are right about the first not being a self-executing function which is why it isn't being executed first.
The first script gets executed first. The function it defines doesn't get executed first (it gets passed to $()). If you stick a breakpoint in that function, then that breakpoint one be hit until the function is called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.