Here is a function that will load CSS files with a success or failure callback. The failure callback will be called just once, if one or more resources fail to load. I think this approach is better than some of the other solutions because inserting a element into the DOM with an HREF causes an additional browser request (albeit, the request will likely come from cache, depending on response headers).
function loadCssFiles(urls, successCallback, failureCallback) {
$.when.apply($,
$.map(urls, function(url) {
return $.get(url, function(css) {
$("<style>" + css + "</style>").appendTo("head");
});
})
).then(function() {
if (typeof successCallback === 'function') successCallback();
}).fail(function() {
if (typeof failureCallback === 'function') failureCallback();
});
}
Usage as so:
loadCssFiles(["https://test.com/style1.css", "https://test.com/style2.css",],
function() {
alert("All resources loaded");
}, function() {
alert("One or more resources failed to load");
});
Here is another function that will load both CSS and javascript files:
function loadJavascriptAndCssFiles(urls, successCallback, failureCallback) {
$.when.apply($,
$.map(urls, function(url) {
if(url.endsWith(".css")) {
return $.get(url, function(css) {
$("<style>" + css + "</style>").appendTo("head");
});
} else {
return $.getScript(url);
}
})
).then(function() {
if (typeof successCallback === 'function') successCallback();
}).fail(function() {
if (typeof failureCallback === 'function') failureCallback();
});
}