21-09-2009

jQuery Insert google analytics with jquery

The following jQuery code will load the google Analytics code on dom ready thus preventing any slowdown in the loading of the page. replace the the UA-xxxxxx-x bit with your your google analytics account id:

jQuery.getScript(gaJsHost + "google-analytics.com/ga.js", function(){
	try{
  		var pageTracker = _gat._getTracker(gaTrackCode);  
		pageTracker._initData();  
		pageTracker._trackPageview();    
	}catch(err){/* handle errrors here */}
});

Comments:

3 comments.
Your comment:

»
Onbeperkt Media 21/10/2009, 11:47 am
That's actually not recommended.

Google Analytics reports whether a visitor has Javascript enabled or disabled (http request detects js). If GA is only loaded (requested) by jQuery, all javascript-disabled visitors will not be registered by Google.

GA script isn't that huge and requesting the script as Google recommends is most reliable for analytics.
Ping 27/10/2009, 8:44 am
The recommended Google method does however at times cause the loading of pages to slow down significantly. Methods like the above do prevent this.
Isaac H. 07/05/2010, 7:26 pm
could someone explain how to use this code, that is, be more specific about the use of the code and explain it step by step, please, I appreciate that."

 

[x]