Yahoo! Web Analytics: Dynamic Tracking Code Loading in HTTPS or HTTP

Monitoring websites with secure pages requires the use of two different sets of Yahoo Web Analytics tracking code, one for secure pages and the other for non-secure pages. The drawback to this's that you're left with inconsistent tracking code across the site and care must be exercised to ensure that the correct tracking code is […]

Monitoring websites with secure pages requires the use of two different sets of Yahoo Web Analytics tracking code, one for secure pages and the other for non-secure pages. The drawback to this's that you're left with inconsistent tracking code across the site and care must be exercised to ensure that the correct tracking code is being used in the right place.

Yahoo! Analytics blog posted a nifty solution "integrate a discriminator according to the protocol used on the page to load only the code necessary for that page." "Additionally, we must know when JavaScript is loaded and execute the tracking code without causing execution errors," stated Yahoo!

The solution is taken in 4 steps:

  1. TrackPage. Page tracking function.
  2. Dynamic loading of JavaScript. Load appropriate JS source from YWA.
  3. Execute TrackPage. Once the JS is loaded, execute TrackPage.
  4. NoScript. Element for non-JavaScript enabled tracking.

Here's the complete code:

<script type="text/javascript">
 function TrackPage(docName, docGroup){
    var _yat;
    if(typeof(docName)=="undefined") docName="";
    if(typeof(docGroup)=="undefined") docGroup="";
    try{
    _yat = YWA.getTracker("1000621731362");
    _yat.setDocumentName(docName);
    _yat.setDocumentGroup(docGroup);
    //_yat.setDomains("*.metriplica.com");
    //_yat.setCookieDomain("www.metriplica.com");
    //_yat.setMemberId("");
    _yat.submit();
    }catch(err){
     if(typeof(console)!="undefined")
      console.log("Error tracking Yahoo: %o", err);
    };
 };
(function(d, t){
 var s, h;
 s = d.createElement(t);
 s.type = 'text/javascript'; s.async = 1;
 s.src = ('https:' == d.location.protocol ? 'https://s' : 'http://d') + '.yimg.com/mi/ywa.js';
 s.onreadystatechange = function () {
  if (js.readyState == 'complete') {
   TrackPage();
  }
 }
 s.onload = function () {
  TrackPage();
 };
 h = d.getElementsByTagName(t)[0];
 h.parentNode.insertBefore(s, h);
})(document, 'script');
</script>
<noscript>
<div><img src="https://a.analytics.yahoo.com/p.pl?a=10001502141662&amp;js=no" width="1" height="1" alt="" / /></div>
</noscript>

[Source]