我一直在使用this function将onload处理程序附加到脚本标记,这似乎是互联网上推荐的方式。
然而,如果页面已经加载(在8中测试),它在Internet Explorer中不起作用。您可以看到它在普通浏览器中有效(加载脚本时会触发警报)。
我错过了什么吗? 谢谢
答案 0 :(得分:87)
你应该拨打jQuery.getScript
,这正是你正在寻找的。 p>
编辑:以下是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 );
答案 1 :(得分: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);