Kelvin
Kelvin

Reputation: 585

How to load external script in sequence

Do anyone has similar experience? I found the jQuery didn't load the script in order. Below is the script I called, I have no idea what the sequence of the code be called. In code, the validation.js is called first and then the c_validation.js, but in the Chrome Javascript Console, the result of loading the script is inverted. Is it caused by the size of the script? How can I force the scripts be loaded one by one?

    $("#tab-4-content").load("/reg.php?id="+this.id+"&ads="+$(this).data('ads')+"&f="+$(this).data('file')+"&mid="+$(this).data('mid'));
    var url = "http://mydomain.com/validation.js";
    $.getScript(url) 
    .done(function() {
        console.log( "Success load validation");
    })
    .fail(function() {
        console.log("Failed load validation");
        });
    var url = "js/c_validate.js";
    $.getScript(url)
        .done(function() {
            console.log("Success load c_validate.js");
        })
        .fail(function() {
            console.log("Failed load c_validate.js");
        });
    $.mobile.changePage("#tab-4");
    $("#terms").html("/dev/terms.inc.html");
}); // tab-3-content click

XHR finished loading: GET "http://dev.mydomain.com/c_by_cat.inc.php?id=code". jquery.js:10306
http://mydomain.com/validation.js js.php?id=code:92
XHR finished loading: GET "http://dev.mydomain.com/js/c_validate.js?_=1405324184667". jquery.js:10306
Failed load c_validate.js js.php?id=code:106
XHR finished loading: GET "http://dev.mydomain.com/reg.php?id=3&ads=1&f=3.png&mid=2". jquery.js:10306
Success load validation 

Upvotes: 0

Views: 99

Answers (1)

freakish
freakish

Reputation: 56587

This happens because you fire parallel requests. You can use something like that:

var get_scripts_in_order = function(urls, def) {
    if (def === undefined) {
        def = $.Deferred();
    }
    var url = urls.pop();
    if (url === undefined) {
        def.resolve();
    } else {
        $.getScript(url)
            .done(function() {
                get_scripts_in_order(urls, def);
            })
            .fail(function() {
                def.reject(url);
            });
    }
    return def.promise();
};

get_scripts_in_order(["script3.js", "script2.js", "script1.js"])
    .done(function() {
        console.log("loaded all scripts");
    })
    .fail(function(url) {
        console.log("fail: "+url);
    });

Note that the order of URLs is reversed due to .pop.

There's an interesting plugin for jQuery which may help you as well:

https://github.com/gnarf/jquery-ajaxQueue

Upvotes: 1

Related Questions