A previous question revealed how to load in jQuery using native JavaScript. che ho usato con successo il codice di richiamata dalla risposta c'è, replicati qui:carico con JavaScript utilizzando Promises
// 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...
});
})();
Come posso ottenere lo stesso risultato utilizzando native JavaScript Promises?
La ragione Chiedo è perché improvvisamente ho bisogno di ricomporre il callback precedente, ed è un pasticcio. Spero che le Promesse siano un modo migliore e non ho alcun reale interesse nell'utilizzo di un framework di caricamento.
Ecco quello che ho finora, ma la promessa finisce sempre respinto: (. Mi dispiace in anticipo per la mia completa ignoranza)
// 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);
});
È necessario continuare a utilizzare il vecchio codice e solo a risolvere la promessa quando jquery è pronto. In questo caso non è necessario rifiutarlo, a meno che jquery non si carichi dopo un periodo di tempo. –