简体   繁体   中英

Google Analytics cookies are not loading in an IF statement

I have the following code:

var selectedLevel = true;
if (selectedLevel === true) {
    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

    try {
        var pageTracker = _gat._getTracker("UA-XXXXXXX-XX"); // <-- The ID _is_ here
        pageTracker._trackPageview();
    } catch(err) {}
}

I am expecting to see cookies being set in FireCookie but I see nothing. The ga.js does appear to be loading in though, according to my Firebug NET tab.

Is there a reason anybody knows of why the cookies wouldn't be getting set?

I suspect that because the try/catch block is in the same script, the line getting the tracker is being executed before the other script loads and fails because _gat isn't defined. Try putting it in its own script block like the Google docs suggest.

<script type="text/javascript">
    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
    try{ 
        var pageTracker = _gat._getTracker("UA-xxxxxx-x");
        pageTracker._trackPageview();
    } catch(err) {} 
</script>

(Another possibility) This sometimes happen because ga.js is not yet loaded . You may

Add a delay:

<script type="text/javascript">
    var pageTracker;

    setTimeout('startGA();', 500);
    function startGA()
    {
        pageTracker = _gat._createTracker("UA-XXXXXX-X");
        pageTracker._trackPageview(); 
    }
</script>

--- credits of above codes snippet from this link

Or a better way:

would be to define pagetracker onload

<script type="text/javascript">
    var pageTracker;

    $(window).load(function(){ 
        pageTracker = _gat._createTracker("UA-XXXXXX-X");       
        pageTracker._trackPageview(); 
    });
</script>

To check whether ga.js is loaded

You may also do this (instead of try catch):

<script type="text/javascript"> 
    var pageTracker;

    if (typeof(_gat) == "object") { 
        pageTracker = _gat._createTracker("UA-XXXXXXX-X"); 
        pageTracker._trackPageview(); 
    } 
</script> 

Just a note - I would recommend the declaration of var pageTracker to be outside of try-catch block or if/else statement. Hope this helps someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM