我想从谷歌的CDN加载jQuery,并在请求成功时执行jQuery代码,但我似乎无法使其正常工作.这是我的代码:
function loadjQuery(success, error) {
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
xhr.onload = function() { success(xhr.status, xhr.readyState); }
xhr.onerror = function() { error(); }
xhr.open("GET", "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js", true);
xhr.send();
}
loadjQuery(
function(status, state) {
console.log(status) // 200
console.log(state) // 4
console.log($('body')) // Uncaught ReferenceError: $ is not defined
},
function() { setTimeout(loadjQuery, 10000); }
);
Run Code Online (Sandbox Code Playgroud)
任何帮助将非常感激
使用以下代码加载JQuery
(function () {
function loadScript(url, callback) {
var script = document.createElement("script")
script.type = "text/javascript";
if (script.readyState) { //IE
script.onreadystatechange = function () {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function () {
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
loadScript("https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js", function () {
//jQuery loaded
console.log('jquery loaded');
console.log($('body') //works
});
})();
Run Code Online (Sandbox Code Playgroud)