由于我的项目要求,我正在动态添加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.")
}
}
您可以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大小写是构造函数时使用。例如
var adder = new Function('a', 'b', 'return a + b');
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句