How to make the page load only after getJSON returns?


I'm retrieving a list in JSON using the jQuery.getJSON function:


This code returns the object perfectly, but the request takes longer than the loading time of the page where I will insert the data. This way, the page loads with the object still null .

How do I make the page load only after the getJSON return?

asked by anonymous 11.09.2014 / 18:02

3 answers


Pass a callback to getJSON :

jQuery.getJSON(url, function(dados) {
    // aqui o json já carregou e pode ser acessado como "dados"
11.09.2014 / 18:23

So, in my opinion, it is the server that should perform the search and embed the data directly on the page that will be served (as a result of processing on the server).

In most cases (and I say this just because, in some cases, such as when we do not have access to the server, it is really justifiable to perform this task via Javascript), there is no purpose in serving a blank page, "frozen" until an AJAX request returns the data from the server. I recommend that you do not use AJAX, and instead generate the page already with the data embedded on the server side.

However, if you need to apply this model, just use the third parameter ( callback ) of the function getJSON() (which is the function to be executed after receiving the response) to proceed with the execution asynchronously:

$.getJSON(v_url, v_data, function(data){

Where data will be the literal object with your data.

If you want a synchronous execution (which, as @bfavaretto pointed out, is the category of a routine call that prevents the program from processing anything else until the calling routine finishes ), , before the previous script, the following excerpt:

    async: false

EDIT : The above excerpt changes how all AJAX requests from then on will be made by jQuery. Since getJSON() is nothing more than an abbreviation of syntax for a% common call, it will suffer the effect of AJAX() as well, but if you just want to do the JSON request synchronously, you you need to restore the configuration to asynchronous mode again after ajaxSetup() :

    async: true
11.09.2014 / 18:28

You can use the $.holdReady() method as follows:

$.getJSON(url, function(json) {
    // algum processamento com o json


So you can use the .ready() method of jQuery to execute your scripts only after json returns.

$(document).ready(function() {
    // código executado depois do carregamento do json

See more information at link .

12.09.2014 / 18:29