[英]JavaScript how to catch event when lazy loaded script is ready?
我有一个延迟加载JavaScript文件,如何在文件中的类准备好使用时捕获事件? 我只需要在特定情况下加载此脚本。 因此它不是通过onload加载的,而是在if子句中加载的。
我从这里得到的延迟加载代码: 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
});
if (s.readyState) s.onreadystatechange = function () {
if (s.readyState === "loaded" || s.readyState === "complete") {
s.onreadystatechange = null;
callback();
}
}; else s.onload = function () {
callback();
};
由于它需要HTTP请求,您应该能够在其上放置一个onload事件。
s.onload = function() {
// do something
}
在“更快的网站”中,Steve Souders提供了一个解决方案,可以在这里看到。
如果我明白你想要正确完成什么。 这就是存在回调方法的原因。
在这里解释得很好在JavaScript中更好地理解回调函数
或者你可以通过ajax获取脚本。 然后你确定在ajax succes事件被触发时加载脚本:)
var onloadCallback = function() {
alert('onload');
}
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.onreadystatechange = function () { // for IE
if (this.readyState == 'complete') onloadCallback();
};
s.onload = onloadCallback; // for other browsers
s.src = 'http://yourdomain.com/script.js';
var x = document.getElementsByTagName('script')[0]
x.parentNode.insertBefore(s, x);
您还可以使用XMLHttpRequest来加载文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.