且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过函数加载Javascript动态脚本...如何再次执行onload或readyState?

更新时间:2023-12-04 22:24:52

您希望加载脚本,而不是文档加载.在此处查看已接受的答案:

You want a script onload, not a document onload. See the accepted answer here:

Internet Explorer中脚本"标记的加载"处理程序

这是令人钦佩的代码:

var head = document.getElementsByTagName("head")[0] || document.documentElement;
var script = document.createElement("script");
if ( s.scriptCharset ) {
    script.charset = s.scriptCharset;
}
script.src = s.url;

// Handle Script loading
    var done = false;

// Attach handlers for all browsers
script.onload = script.onreadystatechange = function() {
    if ( !done && (!this.readyState ||
            this.readyState === "loaded" || this.readyState === "complete") ) {
        done = true;
        jQuery.handleSuccess( s, xhr, status, data );
        jQuery.handleComplete( s, xhr, status, data );

        // Handle memory leak in IE
        script.onload = script.onreadystatechange = null;
        if ( head && script.parentNode ) {
            head.removeChild( script );
        }
    }
};

// Use insertBefore instead of appendChild  to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );