我一直在使用this function将onload处理程序附加到脚本标记,它似乎是通过Internet推荐的方式。
但是,它不能在Internet Explorer中工作,如果页面已经加载(在ie 8中测试过)。你可以看到它在普通浏览器中工作(加载脚本时触发警报)。'onload'处理程序为'脚本'标记在Internet Explorer中
我错过了什么吗?
谢谢
我一直在使用this function将onload处理程序附加到脚本标记,它似乎是通过Internet推荐的方式。
但是,它不能在Internet Explorer中工作,如果页面已经加载(在ie 8中测试过)。你可以看到它在普通浏览器中工作(加载脚本时触发警报)。'onload'处理程序为'脚本'标记在Internet Explorer中
我错过了什么吗?
谢谢
你应该打电话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);
我还与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);
的onload未在IE8和下方被支承。它在IE9标准模式下工作。 – EricLaw 2011-01-30 22:36:49
@EricLaw我不确定你的意思,window.attachEvent('onload',fn);迄今为止一直在为我工作(IE 8)。它也提到[MSDN](http://msdn.microsoft.com/en-us/library/cc197055(v = vs.85).aspx) – 2011-01-30 23:36:12
@NikitaRybak我也试图实现一种方式来加载jQuery的一个脚本(如果尚未加载),然后在加载时调用一个函数。不幸的是,在脚本中没有`onload`。你有没有找到一种方法来做到这一点? – Etherealone 2012-08-17 09:48:09