由于项目的要求,我正在动态添加jQuery。但是,当调用以下函数时,控制台中会显示jQuery is not defined
。但是,如果我在控制台中写alert(jQuery)
它会返回function (a,b){return new m.fn.init(a,b)}
,所以我知道它已加载。有没有人有任何建议?
function AddExternals(){
if (!jQuery){
var jq = document.createElement("script");
jq.type = "text/javascript";
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js";
document.getElementsByTagName("head")[0].appendChild(jq);
console.log("Added jQuery!");
} else {
console.log("jQuery already exists.")
}
}
答案 0 :(得分:1)
您可以使用window.jQuery
来验证是否已加载jQuery
function AddExternals(){
if (!window.jQuery){
var jq = document.createElement("script");
jq.type = "text/javascript";
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js";
document.getElementsByTagName("head")[0].appendChild(jq);
console.log("Added jQuery!");
} else {
console.log("jQuery already exists.")
}
}
AddExternals();
注意:根据js约定,当它是构造函数时使用pascal case。例如
var adder = new Function('a', 'b', 'return a + b');
答案 1 :(得分:0)
来自here
文档发布时会触发DOMContentLoaded事件 完全加载和解析,无需等待样式表,图像, 和子帧完成加载(加载事件可用于检测 一个完整的页面。)
因此,移动您的功能到window.onload
事件
window.onload = function() {
AddExternals()
};
请遵循Praveen的建议。