The solution can be improved a bit I think... First of all, when you use this lines of code:
...
$.get(url, function(){
$('<link>', {rel:'stylesheet', type:'text/css', 'href':url}).appendTo('head');
});
...
You're really making 2 calls to retrieve the css: first in the $.get
itself and a second time when you append the <link>
into the head
. Removing the $.get
will also retrieve the css, but just once:
...
$('<link>', {rel:'stylesheet', type:'text/css', 'href':url}).appendTo('head');
...
But if you need to do more things (eg. loading a script file) while retrieving these css' before calling the callback function I think a better approach for this would be using promises instead of the when...then
solution. You could do something like this:
var requests = []; //array which will contain every request we want to do before calling the callback function
$.map(urls, function(url) { //urls is the array of css files we want to load
var defer = $.Deferred();
defer.promise();
//we add the deferred object to the requests array
requests.push(defer);
var cssEl = $('<link>', { rel: 'stylesheet', type: 'text/css', 'href': url });
cssEl.appendTo('head').on("load", function() {
defer.resolve();
});
});
var anotherRequest = $.ajax({...}); //eg. a script file
requests.push(anotherRequest);
$.when.apply($, requests).done(function() {
// callback when all requests are done
});
This way, if some of the css takes some time to load, the callback function won't be executed until all of them are retrieved.