Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As I said, it's relatively easy to chain Ajax calls with promise objects. Now, it don't see <em>why</em> the scripts have to be loaded one after the other, but you will have a reason for it.</p> <p>First though I would get rid of the <code>switch</code> statement if you are only calling the same function with different arguments. E.g. you can put all the script URLs in a map:</p> <pre><code>var scripts = { '#FFF': '...', '#000': '...' // etc. }; </code></pre> <p>You can chain promises by simply returning another promise from a callback passed to <a href="http://api.jquery.com/deferred.then/" rel="noreferrer"><code>.then</code> <em><sup>[docs]</sup></em></a>. All you need to do is start with a promise or deferred object:</p> <pre><code>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 callbacks deferred.resolve(); </code></pre> <p>In <code>loadScript</code>, you simply return the promise returned from <code>$.getScript</code> or the one returned by <code>.done</code>:</p> <pre><code>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. }); } </code></pre> <p>The scripts will all be called in the order the are access in the loop. Note that if <code>divlist</code> is an array, you really should use normal <code>for</code> loop instead of a <code>for...in</code> loop.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload