Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? I only need to load this script in a specific case. Therefor it is not loaded via onload but in a if clause.

The lazy loading code I took from 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 totally forgot about Ajax! :) I was so focused on my problem that I didn't saw the obviously solution by @Tokimon. The simplest solution via jQuery would then be:

$.getScript('http://yourdomain.com/script.js', function() {
  // callback or use the class directly
});
like image 423
powtac Avatar asked Mar 18 '11 15:03

powtac


1 Answers

if (s.readyState) s.onreadystatechange = function () {
    if (s.readyState === "loaded" || s.readyState === "complete") {
        s.onreadystatechange = null;
        callback();
    }
}; else s.onload = function () {
    callback();
};
like image 145
jasssonpet Avatar answered Oct 25 '22 18:10

jasssonpet