1

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 ?

user3350731
  • 962
  • 1
  • 10
  • 30
  • 2
    Do you have a `` tag at the time the JS executes? Perhaps you're including the script file in the header and not in the bottom of your body? – h2ooooooo May 19 '14 at 13:35
  • has the dom been loaded and is ready? – Daniel A. White May 19 '14 at 13:36
  • 1
    To give you a pretty literal answer -- the source of the error is that document.getElementsByTagName("body")[0] is undefined, which means there isn't a body element at the time it's executing. Now you just have to figure out why. – Sam Hanley May 19 '14 at 13:37
  • you don't really need createElementNS. `document.createElement('img')` or just `var img = new Image();` should do it. – gp. May 19 '14 at 13:38

1 Answers1

5

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.

sergiogarciadev
  • 2,061
  • 1
  • 21
  • 35
  • Might want to link to the [documentation](http://awstats.sourceforge.net/docs/awstats_config.html#MiscTrackerUrl) describing where to put the JS file. – h2ooooooo May 19 '14 at 13:39