开发者

Cannot include a javascript file from an external javascript file in IE6

开发者 https://www.devze.com 2022-12-15 11:17 出处:网络
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:

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


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.


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.


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


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);


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号