According to the Google Analytics Help Center, the tracking code segment of your Analytics website profile must be added into the bottom of your content, immediately before the </body> tag. Sure you remember those days when you were told to put it in the <head>, and to many people’s astonishment when Analytics had an outage of its service loads of websites were just loading and loading while the user were getting no response – kinda new shade of screen death.
There are several ways to load and call Analytics on document load. In the following example I use Scott Andrew’s great addEvent wrapper to handle event attaching.
Tested under Internet Explorer, Mozilla compatibles and Opera. May not work under certain versions of Konqueror and Safari. To address this issue you can use delayed function call.
loadGA is responsible for loading the remote Analytics API. After browser responsed the proper status, we call
callGA, which create another script container using DOM methods, which forces browser to run its content.
A pro of this method is that allows further refinement of your logic – e.g. you can now serve different Analytics code depending on the protocol if you use secure channel.
And that’s all, folks. Comments are welcome at DZone.