$ is not defined error using jQuery and Google Code Repository

我怕爱的太早我们不能终老 提交于 2019-12-02 06:01:17

google.load injects a script element right after itself. So the order in which script tags appear is:

// google loads first
<script src="http://www.google.com/jsapi"></script>

// ask "google" to load jQuery and jQuery UI
<script>
    google.load("jquery", "1");
    google.load("jqueryui", "1");

    // try to use $
    $(function() {
        $("#tabs").tabs();
    });
</script>

// But, jQuery gets included here (after its usage)
<script src="jquery.min.js"></script>

// and jQuery UI gets included here
<script src="jquery-ui.min.js"></script>

Since the usage of $ appears before jQuery is included in document order, $ will not be defined in the second step.

A solution is to break apart the script tags, so that google.load statements appear in their own script tags. So instead if you replace your code with:

<script>
    google.load("jquery", "1");
    google.load("jqueryui", "1");
</script>

<script>
    $(function() {
        $("#tabs").tabs();
    });
</script>

The order of script tags in the document now will be:

// first google loads
<script src="http://www.google.com/jsapi"></script>

// then we ask "google" to load jQuery and jQuery UI
<script>
    google.load("jquery", "1");
    google.load("jqueryui", "1");
</script>

// jQuery loads
<script src="jquery.min.js"></script>

// jQuery UI loads
<script src=".../jquery-ui.min.js"></script>

// now our script can run smoothly
<script>
    $(function() {
        alert($("h1").text());
    });
</script>

Note that the script element containing your jQuery code now appears after jQuery, so your code should work and $ or jQuery should be defined from that point thereon.


However, instead of relying on the behavior of google's loading order, a better solution is to either use the direct links for the libraries, or use a callback.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js"></script>
<script>
    // your jQuery code follows
</script>

Or, use the onLoad callback:

google.load("jquery", "1");
google.load("jqueryui", "1");

google.setOnLoadCallback(function() {
    // jQuery should be define here
    $(function() {
        alert($("h1").text());
    });
});

For some reason I got the same error

I got away with it by adding this script to every page

<script language="javascript" type="text/javascript">
    $j = jQuery.noConflict();
</script>

then using

$j("#tabs").tabs();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!