JavaScript how to catch event when lazy loading script ready?

I have a lazy loadable JavaScript file, how can I catch an event when a class in a file is ready to use? I only need to download this script in a specific case. Therefore, it is not loaded via onload, but in the if condition.

Lazy the download code I took here: 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 completely forgot about Ajax! :) I was so focused on my problem that I did not see the @ Tokimon solution explicitly. The simplest solution through jQuery would be the following:

$.getScript('http://yourdomain.com/script.js', function() {
  // callback or use the class directly
});
+5
source share
5 answers

script ajax. , script ajax succes:)

+1
if (s.readyState) s.onreadystatechange = function () {
    if (s.readyState === "loaded" || s.readyState === "complete") {
        s.onreadystatechange = null;
        callback();
    }
}; else s.onload = function () {
    callback();
};
+3

HTTP-, onload.

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

" -" , .

+1
+1
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 .

+1

All Articles