javascript - How do I ensure that Google Analytics is loaded before calling it's functions? -


after reading blog post, got idea add safety code ensure google analytics objects loaded before calling it's functions.

typicle google analytics code goes like:

var pagetracker = _gat._gettracker("x-uaxxxxx"); pagetracker._trackpageview(); 

and

pagetracker._additem( bla bla ); pagetracker._tracktrans(); 

i have thought of 2 options double ensure _gat-object loaded before use:

1) use jquery.ready call _get-functions. like:

$(document).ready(function() {     var pagetracker = _gat._gettracker("x-uaxxxxx");     pagetracker._trackpageview(); } 

or

2) use javascript timeout

function checkgat() {      if( gat_is_ready ) {         var pagetracker = _gat._gettracker("x-uaxxxxx");         pagetracker._trackpageview();     } else {         settimeout('checkgat()', 1000);     }  }  checkgat() 

what better solution? why? , additional comments?

this unnecessary. use new google analytics asynchronous code; you.

<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';     var s = document.getelementsbytagname('script')[0]; s.parentnode.insertbefore(ga, s);   })();  </script> 

with code, store tracking information in javascript array (called _gaq) in page want. then, executes call google analytics once the ga.js has loaded , ready. in other words, of you, without needing write complex loops, , you'll never have race conditions result in javascript errors.

this has added benefit of being non-blocking , faster.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -