Internet Explorer中"script"标记的"onload"处理程序

Nik*_*bak 51 javascript internet-explorer onload

我一直在使用这个函数将onload处理程序附加到脚本标记,它似乎是互联网上推荐的方式.
然而,如果页面已经加载(在8中测试),它在Internet Explorer中不起作用.您可以看到它在普通浏览器中有效(加载脚本时会触发警报).

我错过了什么吗?
谢谢

SLa*_*aks 88

你应该打电话jQuery.getScript,这正是你正在寻找的.

编辑:这是jQuery的相关源代码:

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 );
Run Code Online (Sandbox Code Playgroud)

  • 只是向其他人说明IE9 +支持script.onload和script.onreadystatechange(http://bit.ly/18gsqtw),因此两个事件都将被触发(即2次调用),这就是为什么需要"完成"的原因.如果您需要将其包装在一个模块中以帮助多个脚本加载,那么很难记住. (7认同)
  • 不会真的有用,因为jquery最初不可用:我必须像这样加载它.但我会查看来源,看看它是否适用于IE.+1有趣的参考,谢谢! (4认同)
  • 我认为"jQuery.handleSuccess(s,xhr,status,data); jQuery.handleComplete(s,xhr,status,data);"可能不是必需的,如果逐字使用会导致错误 (2认同)

小智 10

我也遇到过script.onload = runFunction的问题; 在IE8中.

我尝试了jQuery.getScript,它完全符合我的需求.唯一的缺点是在添加脚本之前必须等待加载jQuery.

但是,由于我的回调函数非常重视jQuery,我发现这是一个非常可接受且非常小的缺点,因为它创建了一个非常易于使用的跨浏览器解决方案.

更新:

这是一种不使用jQuery的方法:

(修改后的解决方案来自:https://stackoverflow.com/a/13031185/1339954)

var url = 'http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js';
var headID = document.getElementsByTagName("head")[0];
var script = document.createElement('script');
script.type='text/javascript';
script.src=url;

//for nonIE browsers
script.onload=function(){
        addVideo();
    }

 //for IE Browsers
 ieLoadBugFix(script, function(){
     addVideo();}
 );

function ieLoadBugFix(scriptElement, callback){
        if (scriptElement.readyState=='loaded' || scriptElement.readyState=='completed') {
             callback();
         }else {
             setTimeout(function() {ieLoadBugFix(scriptElement, callback); }, 100);
         }


 }

headID.appendChild(script);
Run Code Online (Sandbox Code Playgroud)

  • 看起来jQuery设法在没有轮询的情况下完成它.尝试onreadystatechange而不是设置超时 (2认同)