Skip to content Skip to sidebar Skip to footer

How To Wait For Another Js To Load To Proceed Operation?

I have an issue. One of my JS scripts needs Facebook SDK and Twitter widgets JS to load first. Facebook creates FB object, Twitter creates twttr object. Both of them create these o

Solution 1:

If the scripts are loaded in the normal, synchronous way, then just make sure that your<script> include appears after the library scripts in the document's <head>. If, on the other hand, those scripts are loading objects asynchronously (as seems to be the case), then create something like this:

functionwhenAvailable(name, callback) {
    var interval = 10; // mswindow.setTimeout(function() {
        if (window[name]) {
            callback(window[name]);
        } else {
            whenAvailable(name, callback);
        }
    }, interval);
}

And use it like this:

whenAvailable("twttr", function(t) {
    // do something
});

The function given in the second argument to whenAvailable will not execute until twttr is defined on the global window object. You can do the same thing for FB.

Important note: Those libraries probably also provide some built-in way to execute code after they have loaded. You should look for such hooks in their respective documentation.

Solution 2:

Have you put your script to be executed on page load? (ie. body onload="do_this ();")

That should make your code execute once all external resources has been loaded.


Regarding the use of setTimeout

setTimeout will return immediately, if you'd like to wait for certain variable to be defined, use something as the below.

functionwhen_external_loaded (callback) {
  if (typeofFB === 'undefined' || typeof twtter === 'undefined') {
    setTimeout (function () {
       when_external_loaded (callback);
    }, 100); // wait 100 ms
  } else { callback (); }
}

...

when_external_loaded (function () {
    alert (FB);
    alert (twtter);
});

Solution 3:

constcheckIfLoaded = ('lib', cb) => {
  const interval = setInterval(() => {
    if (lib) {
      typeof cb === 'function' && cb();
      clearInterval(interval);
    } else {
      console.log('not yet');
    }
  }, 100);
}

Solution 4:

If the Facebook scripts are being loaded asynchronously, Facebook has a supported way to execute code when it's library loads which should be much more efficient than polling for it. See this answer for an example: https://stackoverflow.com/a/5336483/816620.

If the Facebook scripts are being loaded synchronously, then you don't have to wait for them - they will load before any other scripts after them run.

Post a Comment for "How To Wait For Another Js To Load To Proceed Operation?"