I first ran into this error when I started using jQuery. It turns out it’s a somewhat common (beginner’s) mistake of trying to run a script without first waiting for jQuery to finish loading, which results in a race condition. The easiest fix for this is to make sure jQuery has its own separate script tag right above your own jQuery-dependent script:
<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"></script> <script src="myscript.js" type="text/javascript"></script>
This will ensure that myscript.js is loaded only after jQuery is loaded. Of course there are other ways to do this, notably John Resig’s degrading script pattern, but the above solution will at least solve the “$ is not defined” error, which is priority.
However, this may not be enough. Theoretically it’s possible that jQuery doesn’t get loaded (due to some network error) but your script does. In that case we come full circle to our original “$ is not defined” problem. So how do we prevent this?
The first thing I thought of was to make sure $ is defined by wrapping it in an if-then statement. Note that this does NOT fix the problem:
//note: this method DOES NOT work!
if ($) { //check if $ is defined - but this check results in an error!
$("#myselector").click (function () {}); //my jQuery code here
}
With the above code, we run into the same problem! Arg! But don’t despair. It turns out we need to prevent this sort of error by using the good old try-catch block:
try {
$("#myselector").click (function () {}); //my jQuery code here
} catch (e) {
console.log (e.message); //this executes if jQuery isn't loaded
}
And it works! If $ is undefined (and therefore jQuery isn’t loaded), the error is caught and handled instead of exploding.
Since we don’t live in a perfect world, it would be a good idea to assume that jQuery will not always be loaded and that this “network error” scenario may well occur, so it would be good practice to run a check like this before executing code that depends on jQuery (and likewise for other scripts with other dependencies!).


![[转]常见的nginx的配置选项](http://www.jiunile.com/wp-content/themes/xupeng/images/random/5.jpg)





最新评论
如何建立自己的特征码呢? 我
怎么修改啊,帮帮忙啊,,,,
你好,我照您的方法做了之后,
可否请教,要如何的调整呢?
拜读……
您这个是是2003的服务器
安装上以后 发现运行了 直接
有点意思,不错!
你QQ号多少?我是智生道顾问
请问你是怎么修改的啊?为什么