Using getScript synchronously Using getScript synchronously javascript javascript

Using getScript synchronously


This worked for me, and may help you.

$.ajax({    async: false,    url: "jui/js/jquery-ui-1.8.20.min.js",    dataType: "script"});

Basically, I just bypassed the shorthand notation and added in the async: false


As I said, it's relatively easy to chain Ajax calls with promise objects. Now, it don't see why the scripts have to be loaded one after the other, but you will have a reason for it.

First though I would get rid of the switch statement if you are only calling the same function with different arguments. E.g. you can put all the script URLs in a map:

var scripts = {    '#FFF': '...',    '#000': '...'    // etc.};

You can chain promises by simply returning another promise from a callback passed to .then [docs]. All you need to do is start with a promise or deferred object:

var deferred = new $.Deferred();var promise = deferred.promise();for (var i in divlist) {    // we need an immediately invoked function expression to capture    // the current value of the iteration     (function($element) {        // chaining the promises,         // by assigning the new promise to the variable        // and returning a promise from the callback        promise = promise.then(function() {            return loadScript(                scripts[$element.css("background-color")],                 $element            );        });    }($('#' + divlist[i])));}promise.done(function() {    // optional: Do something after all scripts have been loaded});// Resolve the deferred object and trigger the callbacksdeferred.resolve();

In loadScript, you simply return the promise returned from $.getScript or the one returned by .done:

function loadScript(script_url, $element){    // Unrelated stuff here!!!    return $.getScript(script_url).done(function(){        //  Unrelated stuff here        // do something with $element after the script loaded.    });}

The scripts will all be called in the order the are access in the loop. Note that if divlist is an array, you really should use normal for loop instead of a for...in loop.


Do you know that $.getScript accepts a callback function that is called synchronously after the script is loaded?

Example:

$.getScript(url,function(){//do after loading script});

I have 2 more solutions: a pure js one and one for multiple js load.