A previous question revealed how to load in jQuery using native JavaScript. I've successfully used the callback code from the answer there, replicated here:
// Anonymous "self-invoking" function
(function() {
// Load the script
var script = document.createElement("SCRIPT");
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName("head")[0].appendChild(script);
// Poll for jQuery to come into existance
var checkReady = function(callback) {
if (window.jQuery) {
callback(jQuery);
}
else {
window.setTimeout(function() { checkReady(callback); }, 100);
}
};
// Start polling...
checkReady(function($) {
// Use $ here...
});
})();
How can I accomplish the same thing using native JavaScript Promises?
The reason I ask is because I suddenly need to chain off of the earlier callback, and it's a friggin' mess. I'm hoping Promises are a better way, and I have no real interest in using a loader framework.
Here's what I've got so far, but the Promise always ends up rejected:
// This code doesn't work quite right.
// Poll for jQuery to come into existance using a Promise
var jQueryReady = new Promise(
function(resolve, reject) {
// Load jQuery
var script = document.createElement('SCRIPT');
script.type = 'text/javascript';
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js';
document.getElementsByTagName('head')[0].appendChild(script);
if (window.jQuery) {
resolve("YAY");
} else {
reject("UGH");
}
});
jQueryReady.then(
function(success) {
console.log(success);
},
function(error) {
console.error("Really helpful error:", error);
});
(I'm sorry in advance for my complete ignorance.)