我一直在使用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