views:

279

answers:

5

My problem is that I need to dynamically include a javascript file from another external javascript file. I'm trying to do it by using this function:

function addCustomScriptTag(url) {  
    var scriptTag=document.createElement('script');  
    scriptTag.type = 'text/javascript';  
    scriptTag.src=url;  
    var myElement = document.getElementsByTagName("head")[0];  
    myElement.appendChild(scriptTag);  
}

The problem happens only in IE6 where trying to append to the head element causes an 'operation aborted' error.

Any help would be appreciated

A: 

Append it to the body then. Javascript doesn't have to go exclusively in the <head> of your document.

Erik
If you append to the body, the error still occurs in IE6 and introduces the problem to IE7.
Ben
You've having another problem then, I just tested your script by including a script that has alert('hi'); in IE6 works fine.
Erik
Erik: I'm able to replicate the problem as he described
Justin Searls
A: 

Consider using a library like jQuery and then just use the equivalent (if not using jQuery) of getScript. This will handle cross-browser quirks and inconsistencies for the most part.

thenduks
We are using a vendor solution and we can't edit the source. What we are trying to load dynamically is JQuery
Ben
A: 

I think it's because IE6 doesn't support getElementsByTagName(), try replacing it with document.body.

ZippyV
+2  A: 

It depends when you add it to the head DOM element. Operation aborted occurs in all versions of IE because you're trying to modify a DOM element via JavaScript before that DOM element has finished loading, http://support.microsoft.com/default.aspx/kb/927917.

If you need this script loaded right away, you could do an old school document.write to add the script tag, e.g.

<head>
      <script>document.write('<script src='yourUrl.js'><\/scr'+'ipt>');</script>
</head>

Otherwise call your function in the body onload via plain old JavaScript or via a framework like jQuery a la document.ready.

nickyt
A: 

I steal from the jQuery source:

var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function(){
    if ( !done && (!this.readyState ||
            this.readyState == "loaded" || this.readyState == "complete") ) {
        done = true;
        success();
        complete();
        // Handle memory leak in IE
        script.onload = script.onreadystatechange = null;
        head.removeChild( script );
    }
};

head.appendChild(script);
cobbal