Best practice to combine different Javascript SDKs callbacks

108 Views Asked by At

I've came across this situation a few times before and always found a tricky way to make it work but I'd like to know if there's a best practice for that: Sometimes you have to use several JavaScript SDKs on a page example: Google jsapi and jQuery.

Google calls this function when the SDK is ready to be used:

google.setOnLoadCallback(MyFunction);

jQuery does everything in this callback:

document.ready();

What if I want to manipulate the dom using jQuery AFTER Google's callback. What's the best way to tell the browser: "Wait for jQuery AND Google to be ready and do the stuff..." Is it best to have the jQuery callback nested inside Google callback? Or the other way round? I'm a bit confused.

2

There are 2 best solutions below

0
On

You can do this in different ways, one of which is to use a global variable;

var googleLoaded = false;

google.setOnLoadCallback(function(){
   googleLoaded = true;
   mainCallback();
});

document.ready(mainCallback);

function mainCallback(){ 
  if(googleLoaded){
    ...
    ...
  }
}

As a general solution, you can do as given below

var jsLibsToLoad = 5;

jsLib1.onLoad(mainCallback);
jsLib2.onLoad(mainCallback);
jsLib3.onLoad(mainCallback);
jsLib4.onLoad(mainCallback);
jsLib5.onLoad(mainCallback);

function mainCallback(){ 
  if(!(--jsLibsToLoad)){
    ...
    ...
  }
}
0
On

I would recommend you to use some AMD tool like RequireJS. RequireJS is a JavaScript file and module loader, and it is really good with dependancy management. In your particular case (using of some traditional/legacy "browser globals" scripts) you should additionally use Shim Config.

At the start using AMD is a little bit tricky, but it gave a great benefits when you get used to it. It will improve the speed and quality of your code.