JQuery getScript

I'm stuck right now using a few JavaScript libraries that MUST load in a very specific order. Since jQuery getScript () is asynchronous, it starts loading all scripts very quickly and, as they are completed, runs them. Since they do not execute in order, I get a few errors coming from libraries.

Unfortunately, I cannot modify or modify any of these libraries. What I'm trying to do is use a method that loads the JavaScript library, and in the callback it calls itself until it finishes loading all the libraries.

This works for the first file. When the second file appears, it loses context inside the callback, and I can no longer call the recursive method.

Any ideas?

Paired version of the code:

function loadFiles (CompletedCallback) { var Files = getFiles(); // This is an array of js files to load var currentFileIndex = 0; function processFile (file) { $.getScript(file[currentFileIndex], $.proxy(function () { ++currentFileIndex; if (currentFileIndex === Files.length) { CompletedCallback(); } else { processFile(Files[currentFileIndex]); } }, this); }; processFile(Files[currentFileIndex]); }; 
+8
javascript jquery
source share
3 answers

I'm not sure what happened to your code, but here is how I would do it:

 function loadOrdered(files, callback) { $.getScript(files.shift(), function() { files.length ? loadOrdered(files, callback) : callback(); }); } 

change, more pleasant version:

 function loadOrdered(files, callback) { $.getScript(files.shift(), files.length ? function(){loadOrdered(files, callback);} : callback ); } 

or even better if you don’t need old browsers or implement Function.prototype.bind yourself (with support for binding arguments too, and not just this context):

 function loadOrdered(files, callback) { $.getScript(files.shift(), files.length ? loadOrdered.bind(null, files, callback) : callback ); } 
+9
source share

You can make calls with synchronization:

 $.ajaxSetup({async: false}); $.getScript('library.js'); $.ajaxSetup({async: true}); 
+9
source share

simple form:

 function getScript(url){ $.ajax({url: url, type: 'post', async: false}); } 

using:

 getScript(a_url); 
0
source share

All Articles