简体   繁体   English

JavaScript如何在延迟加载脚本准备好时捕获事件?

[英]JavaScript how to catch event when lazy loaded script is ready?

I have a lazy loading JavaScript file, how can I catch the event when the class in the file is ready for usage? 我有一个延迟加载JavaScript文件,如何在文件中的类准备好使用时捕获事件? I only need to load this script in a specific case. 我只需要在特定情况下加载此脚本。 Therefor it is not loaded via onload but in a if clause. 因此它不是通过onload加载的,而是在if子句中加载的。

The lazy loading code I took from here: http://friendlybit.com/js/lazy-loading-asyncronous-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?
}

Update: 更新:
Sorry guys, I totally forgot about Ajax! 对不起,伙计们,我完全忘记了Ajax! :) I was so focused on my problem that I didn't saw the obviously solution by @Tokimon. :)我非常专注于我的问题,我没有看到@Tokimon明显的解决方案。 The simplest solution via jQuery would then be: 通过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();
};

As it requires a HTTP request, you should be able to put an onload event on it. 由于它需要HTTP请求,您应该能够在其上放置一个onload事件。

s.onload = function() {
  // do something
}

In 'Even Faster Web Sites' Steve Souders offer a solution, which can be seen here . 在“更快的网站”中,Steve Souders提供了一个解决方案,可以在这里看到。

If I understand what you want to accomplish correctly. 如果我明白你想要正确完成什么。 This is why callback methods exist. 这就是存在回调方法的原因。

Explained pretty well here Getting a better understanding of callback functions in JavaScript 在这里解释得很好在JavaScript中更好地理解回调函数

Or you could get the script via ajax. 或者你可以通过ajax获取脚本。 Then you are sure that the script is loaded when the ajax succes event is fired :) 然后你确定在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);   

You could also use an XMLHttpRequest to load the file. 您还可以使用XMLHttpRequest来加载文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM