I'm currently stuck using several JavaScript libraries that MUST load in a very specific order. Since jQuery's getScript() is asynchronous it starts downloading all of the scripts very quickly and, as they finish, executes them. Since they do not execute in order I get multiple errors coming from the libraries.
Unfortunately I cannot change or modify any of these libraries. What I'm attempting to do is use a method that downloads a JavaScript library and, in the callback, have it call itself until it's finished loading all of the libraries.
This works for the first file. When the second file comes around it loses context inside of the callback and I can't call my recursive method anymore.
Any ideas?
A paired-down 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]);
};
$.proxy
? You aren't referring tothis
in the anonymous function – Complacent