I have a problem synchronizing the loading of scripts and executing them with jQuery.
What I have looks similiar to this:
// Load Libraries in 'when'
$.when(
    loadJSFile("lib1.js"),
    loadJSFile("lib2.js")
    loadJSFile("lib3.js")
).then(function() {
    // Load JS files that use the library files
    loadJSFile("file1.js");
    loadJSFile("file2.js");
    loadJSFile("file3.js");
    // needs to return deferred object...
}).then(function() {
    // Call functions declared in file1, file2 and file3
    func1();
    func2();
    func3();
});
loadJSFile loads a javascript file via $.getScript, if it's not already included in in the DOM, returning the $.getScript Promise, or not returning anything, if it's already included.
I think the first then call has to return a Promise/Deferred, but how do I do that with 3 Deferred objects?
The code above calls the 3 functions (func1, func2 and func3) before file1 to file3 are loaded...
I think the first then call has to return a Promise/Deferred, but how do I do that with 3 Deferred objects?
You're already doing this for the first set of scripts - $.when returns  a promise that resolves when all of its promise arguments have resolved.
You should use it for the second set as well:
$.when(
    loadJSFile("lib1.js"),
    loadJSFile("lib2.js")
    loadJSFile("lib3.js")
).then(function() {
    // Load JS files that use the library files
    return $.when(
      loadJSFile("file1.js"),
      loadJSFile("file2.js"),
      loadJSFile("file3.js")
    )
}).then(function() {
    // Call functions declared in file1, file2 and file3
    func1();
    func2();
    func3();
});
However, since you're apparently using this for async script loading, you may want to look into a more complete solution like RequireJS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With