LINGS
LINGS

Reputation: 3630

Check if a javascript has loaded and then call another javascript

I have a javascript which gets JSON data from URL and loads the data on to the page, then I want to call another javascript to add the slide effects.

There is a simpler solution, i.e using setTimeout. But this solution is not complete because getting data from a URL does not have a fixed amount of time. It varies on every call.

Hence I want to check if my first javascript has loaded and then I want to call the second javascript.

Upvotes: 0

Views: 254

Answers (1)

Aadaam
Aadaam

Reputation: 3739

JavaScript is an asynchronous language, or at least, its HTTP API is (mostly) asynchronous.

You shouldn't use settimeout, but you should use asynchronous chaining instead for building a list of causal events. There's a big bunch of libraries out there to assist this, like http://www.infoq.com/articles/surviving-asynchronous-programming-in-javascript

If you're loading content from your own site, then there'll be an onsuccess/oncomplete event when the JSON finally gets loaded, you can assign a callback to it. How it is actually called depends on your javascript framework if you use one.

If you're using data from a remote site in a format called JSONP, you're to define a callback to it, it should be a public function name, like onMyDataArrived. You should add your callback code there. Some frameworks hide this detail from you, they generate a random function which they remove when the data has arrived, and provide an API similar to onSuccess / onComplete instead.

Nowadays, the most popular javascript framework is jQuery, where you can do such things, like:

$.ajax({
    url: 'give_me_my_json.php',
    dataType: 'json', 
    success: function(data){
         //call your second javascript
    }, 
    error: function(){
         //WHOOOPSIE... data could not be loaded
    }
});

Upvotes: 2

Related Questions