我有一個延遲加載JavaScript文件,當文件中的類準備好使用時,如何捕獲事件?我只需要在特定情況下加載此腳本。因此它不是通過onload加載的,而是在if子句中加載的。JavaScript如何在延遲加載的腳本準備就緒時捕獲事件?
延遲加載代碼,我從這裏拿了:http://friendlybit.com/js/lazy-loading-asyncronous-javascript/
if (externalClassRequired) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'http://yourdomain.com/script.js';
var x = document.getElementsByTagName('script')[0]
x.parentNode.insertBefore(s, x);
// When do I know when the class named "geo" is available?
}
更新:
對不起球員,我完全忘了Ajax的! :)我非常關注我的問題,我沒有看到@Tokimon的明顯解決方案。通過jQuery最簡單的解決方案將是:
$.getScript('http://yourdomain.com/script.js', function() {
// callback or use the class directly
});
忘記了Ajax!謝謝! – powtac 2011-03-19 14:05:12