javascriptawstats

The source of the error : document.getElementsByTagName(...)[0] is undefined


I'm using an awstats js tracker file awstats_misc_tracker.js and as soon as I include it, it shows this error in my console :

TypeError: document.getElementsByTagName(...)[0] is undefined
     document.getElementsByTagName("body")[0].appendChild(l);

Here's the part that render this error :

var imgsrc1 = awstatsmisctrackerurl+'?screen='+TRKscreen+'&win='+TRKwinsize+'&cdi='+TRKcdi+'&java='+TRKjava;
var imgsrc2 = '&shk='+TRKshk+'&svg='+TRKsvg+'&fla='+TRKfla+'&rp='+TRKrp+'&mov='+TRKmov+'&wma='+TRKwma+'&pdf='+TRKpdf+'&uid='+TRKuserid+'&sid='+TRKsessionid;
//alert(imgsrc1);
//alert(imgsrc2);
var imgsrc=imgsrc1+imgsrc2;
if( document.createElementNS ) {
    var l=document.createElementNS("http://www.w3.org/1999/xhtml","img");
    l.setAttribute("src", imgsrc );
    l.setAttribute("height", "0");
    l.setAttribute("width", "0");
    l.setAttribute("border", "0");
    document.getElementsByTagName("body")[0].appendChild(l);
} else {
    document.write('<img style="display:none;" src="'+ imgsrc +'" height="0" width="0" border="0" />')
}

Can anyone please show me the sourse of this error and how I can prevent it ?


Solution

  • You are including the script on the head prior to definition of the body.

    The script is parsed and executed as it is found in the HTML file.

    You should include this script after the body has been declared.

    A recommended location to include all the javascript is at bottom of the HTML file, but it sometimes break legacy code.

    Another way is to execute the script after on the onload page event or use query and the 'ready' function.