Have you ever wanted to do this?
$.when($.getStylesheet('css/main.css'), $.getScript('js/main.js'))
.then(function () {
console.log('the css and js loaded successfully and are both ready');
}, function () {
console.log('an error occurred somewhere');
});
Well, now you can! I have created an alternative to $.getScript
that handles stylesheets. I called it $.getStylesheet for obvious reasons.
It implements the $.Deferred object, which allows for chaining and pseudo-promises-style code. Just like $.ajax
, $.post
, and $.get
. This also means you would have access to all the other methods on that object too, this means: .then()
, .always()
, .done()
, and .fail()
.
Here is the little function for $.getStylesheet. It is just hosted on Github gist, so I can update it if I need to:
You can see this is pretty simple. Just add the function after your jQuery script, or somewhere in your main script file.