6

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
});
powtac
  • 40,542
  • 28
  • 115
  • 170

5 Answers5

3
if (s.readyState) s.onreadystatechange = function () {
    if (s.readyState === "loaded" || s.readyState === "complete") {
        s.onreadystatechange = null;
        callback();
    }
}; else s.onload = function () {
    callback();
};
jasssonpet
  • 2,079
  • 15
  • 18
1

As it requires a HTTP request, you should be able to put an onload event on it.

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

In 'Even Faster Web Sites' Steve Souders offer a solution, which can be seen here.

Mads Mogenshøj
  • 2,063
  • 1
  • 16
  • 23
1

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

Community
  • 1
  • 1
Matthew Vines
  • 27,253
  • 7
  • 76
  • 97
1

Or you could get the script via ajax. Then you are sure that the script is loaded when the ajax succes event is fired :)

Tokimon
  • 4,072
  • 1
  • 20
  • 26
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);   

You could also use an XMLHttpRequest to load the file.

Josiah Ruddell
  • 29,697
  • 8
  • 65
  • 67