我相信我已經解決了我問的問題,但事實證明這並不能解決我實際遇到的問題。好吧。這是我的解決方案:
我們希望在瀏覽器完成嘗試加載第三方腳本後運行一些代碼,以便我們可以檢查它是否成功加載。我們通過限制後備腳本的負載僅在第三方腳本運行或失敗後才能實現。然後,回退腳本可以檢查第三方腳本是否創建了它應該設置的全局變量。
跨瀏覽器的按順序腳本加載啓發http://www.html5rocks.com/en/tutorials/speed/script-loading/。
var fallbackLoader = doc.createElement(script),
thirdPartyLoader = doc.createElement(script),
thirdPartySrc = '<URL to third party script>',
firstScript = doc.getElementsByTagName(script)[0];
// Doesn't matter when we fetch the fallback script, as long as
// it doesn't run early, so just set src once.
fallbackLoader.src = '<URL to fallback script>';
// IE starts fetching the fallback script here.
if('async' in firstScript) {
// Browser support for script.async:
// http://caniuse.com/#search=async
//
// By declaring both script tags non-async, we assert
// that they need to run in the order that they're added
// to the DOM.
fallbackLoader.async = thirdPartyLoader.async = false;
thirdPartyLoader.src = thirdPartySrc;
doc.head.appendChild(thirdPartyLoader);
doc.head.appendChild(fallbackLoader);
} else if(firstScript.readyState) {
// Use readyState for IE 6-9. (IE 10+ supports async.)
// This lets us fetch both scripts but refrain from
// running them until we know that the fetch attempt has
// finished for the first one.
thirdPartyLoader.onreadystatechange = function() {
if(thirdPartyLoader.readyState == 'loaded') {
thirdPartyLoader.onreadystatechange = null;
// The script-loading tutorial comments:
// "can't just appendChild, old IE bug
// if element isn't closed"
firstScript.parentNode.insertBefore(thirdPartyLoader, firstScript);
firstScript.parentNode.insertBefore(fallbackLoader, firstScript);
}
};
// Don't set src until we've attached the
// readystatechange handler, or we could miss the event.
thirdPartyLoader.src = thirdPartySrc;
} else {
// If the browser doesn't support async or readyState, we
// just won't worry about the case where script loading
// fails. This is <14% of browsers worldwide according to
// caniuse.com, and hopefully script loading will succeed
// often enough for them that this isn't a problem.
//
// If that isn't good enough, you might try setting an
// onerror listener in this case. That still may not work,
// but might get another small percentage of old browsers.
// See
// http://blog.lexspoon.org/2009/12/detecting-download-failures-with-script.html
thirdPartyLoader.src = thirdPartySrc;
firstScript.parentNode.insertBefore(thirdPartyLoader, firstScript);
}
如何檢查腳本中是否存在某些內容。就像腳本包含某個對象一樣,查找那個 –
@CrayonViolent,很容易確定腳本已經加載。但是,我需要知道何時檢查。如果我檢查得太快,腳本甚至不會被下載。我需要知道如何區分「尚未裝載」和「因爲放棄而永遠不會裝載」。如果我可以確定我的支票在腳本處理完成後運行,那麼我就全部設置好了。 –
好吧,在腳本中檢查一個獨特的東西將是你最可靠的方法。但我真的不認爲有一種方法可以在x時間內每隔100ms左右使用'setTimeout'並在此之後放棄。這就是我在這樣的情況下所做的,到目前爲止我還沒有找到更好的方法。我現在不認爲存在:/ –