我需要在js文件中包含jQuery,因为它将作为外部脚本加载。
这是我的代码:
function addjQuery() {
if (!window.jQuery) {
var jq = document.createElement("script");
jq.type = "text/javascript";
jq.src = "https://code.jquery.com/jquery-3.2.1.min.js";
document.getElementsByTagName("head")[0].appendChild(jq);
console.log("Added jQuery!");
} else {
console.log("jQuery already exists.")
}
}
addjQuery();
jQuery(function($) {
$(document).ready(function() {
});
});
但是会发生错误:
未捕获的ReferenceError:未定义jQuery
即使我在chrome开发工具的控制台上运行“ jQuery”或“ $”,它也能正常工作。
有什么问题?
最佳答案
jQuery()
函数在从脚本标签加载jQuery之前触发-您可以添加onload
事件处理程序以在脚本下载完成后触发它:
function addjQuery() {
if (!window.jQuery) {
var jq = document.createElement("script");
jq.type = "text/javascript";
jq.src = "https://code.jquery.com/jquery-3.2.1.min.js";
document.getElementsByTagName("head")[0].appendChild(jq);
jq.onload = initjQuery;
console.log("jQuery is loaded!");
} else {
console.log("jQuery already exists.")
}
}
function initjQuery () {
jQuery(function($) {
$(document).ready(function() { });
});
}
addjQuery();
关于javascript - Uncaught ReferenceError:即使在控制台上也无法定义jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43310984/