The previous question showed how to load jQuery using embedded JavaScript. I 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'm asking is because I suddenly need to disconnect from the previous callback, and this is an unpleasant mess. I hope Promises is the best way and I have no real interest in using the loader framework.
Here is what I have so far, but the promise always ends 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 apologize for my complete ignorance.)
source share