I am working on asynchronous calls with $.getScript which will load the scripts I need for specific pages. I grab the scripts via an AJAX call to get the scripts I need and then load them in order with the $.when function, I am not sure why the .done() calls immediately, not when the scripts have loaded entirely and placed in the DOM, ready to be used.
For example, the AJAX call returns this:
['js/jquery.cookie.js', 'js/leaflet.js', 'js/index.js']
With this code:
var loadScripts = function(callback)
{
$.getJSON('url.php', function(response)
{
$['when'].call(this, response).done(function()
{
callback();
});
});
};
Calling it by:
loadScripts(function()
{
// All scripts are loaded and ready to use
// but the callback is fired immediately
// L is undefined
var map = L.map('map-view').setView([51.505, -0.09], 13);
});
I don't want to use a library such as Head.js or Require.js, I need a simple script that can load and wait till the loaded functions are in place that can be used. Please note that the scripts list can change and the order as well, so doing $.when($.getScript(), $.getScript()).done() won't be what I am looking for.
How can I approach this?
1 Answer 1
Your ajax call is returning an array of strings, not deferred objects. You need to actually make those strings deferred objects by requesting them with jQuery.getScript and storing the return value.
var loadScripts = function(callback) {
$.getJSON('url.php', function(response) {
var defArr = $.map(response,function(url) {
return $.getScript(url);
});
$.when.apply(,ドル defArr).done(callback);
});
};
11 Comments
setTimeout of 2 seconds, it will work. This is what I have a problem with because I need it to wait till the function is ready to use.defArr) is an array of objects that contain a promise method.object with the AJAX functions..apply, not .call. dohExplore related questions
See similar questions with these tags.