考虑保存在 script.js 中的脚本:
if ((typeof window.jQuery) == "undefined") {
var js = document.createElement("script");
var he = document.getElementsByTagName('head')[0];
js.type = "text/javascript";
js.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js";
he.appendChild(js);
}
$('document').ready(function(){
alert('testing');
});
然后是一个像这样的基本 html 页面:
<html>
<head>
</head>
<body>
</body>
</html>
<script src=script.js></script>
这会导致错误:
ReferenceError: $ is not defined
script.js
Line 8
为什么没有定义$?首先是 if 之间的代码,然后是代码 ready()
。这会将回调函数中的代码排队,以便在加载文档时正确调用?
如果我查看 Firebug 中的代码,jQuery 已正确加载。这会发生在 document.read
之后吗?还是我在这里错过了什么?
最佳答案
如果您坚持以这种方式加载脚本,请让浏览器在实际准备好使用时通知您。
if (typeof jQuery !== "function") {
var js = document.createElement("script");
var he = document.getElementsByTagName('head')[0];
js.type = "text/javascript";
js.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js";
he.appendChild(js);
js.addEventListener("load", function () {
alert(typeof $); // function
});
}
alert(typeof $); // undefined
旁注:通常最好严格检查类型。如果 window.jQuery
是一个对象、数字或字符串,您的代码不应该接受它。
关于javascript - $ 未定义,当试图动态加载 jQuery 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17913566/