Grcn Grcn - 6 months ago 19
Javascript Question

Jquery function return order issue

In JavaScript, I am calling same function 3rd times but return order changes every time. You can see my code in the below. Sometimes page1.html is first loaded sometime page2.html

How can I solve this issue?

Thanks in advance

$(document).ready(function () {
$("#button").click(function () {
addHtml('page1');
addHtml('page2');
addHtml('page3');
});
});

function addHtml(url) {
if ($("#" + url).length == 0) {
$.get(url+'.html', function (result) {
$('.divtest').append(result);
});
}
};

Answer

A simple solution :

$(document).ready(function () {
    $("#button").click(function () {
        addHtml('page1', function(){
          // page 1 added
          addHtml('page2', function(){
            // page 2 added
            addHtml('page3', function(){
              // All HTML added
            });
          });
        });
    });
});

function addHtml(url, callback) {
    if ($("#" + url).length == 0) {
        $.get(url+'.html', function (result) {
            $('.divtest').append(result);
            return callback();
        });
    }
};