未捕获的ReferenceError:当jquery.js位于文档末尾时,未定义$ [英] Uncaught ReferenceError: $ is not defined when jquery.js is at end of document

查看:69
本文介绍了未捕获的ReferenceError:当jquery.js位于文档末尾时,未定义$的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目,其中所有JS文件都在页脚中引用,建议用于页面加载的速度,包括指向Jquery文件的链接。这段代码产生一个未捕获的ReferenceError,我假设因为在调用脚本之前尚未定义Jquery:

I have a project where all the JS files are referenced in the footer, as is recommended for speed of page loading, including the link to the Jquery file. This code produces an "Uncaught ReferenceError", I assume because Jquery has not been defined before my script is called:

<html>
    <head>
        <link rel="stylesheet" type="text/css" href="css/bootstrap.css">
    </head>
    <body>
        <p>
            <a href="#" data-toggle="popover" title="first popover" id="example">hover over me</a>
        </p>
        <script type="text/javascript"> 
            $(function(){
                $('#example').popover({ trigger:'hover' });
            })
        </script>

        <script type="text/javascript" src="js/jquery.min.js"></script>
        <script type="text/javascript" src="js/bootstrap.js"></script>
    </body>
</html>

如果我将Jquery链接移动到标题,那么代码运行正常,但这会减慢页面加载时间。

If I move the Jquery link to the header, then the code runs fine, but this will slow the page loading time.

有没有更好的方法来声明我的函数,以便它不会抛出此UncaughtReference错误,或者保持头部中的Jquery链接是最佳解决方案?

Is there a better way to declare my function so that it does not throw this UncaughtReference error, or is keeping the Jquery link in the head the best solution?

推荐答案

这是因为你试图在 jQuery > jQuery 已加载。您需要在文档的头部放置像 jQuery 这样的库

It is because you are trying to use jQuery before jQuery has been loaded. You need to put libs like jQuery in the head of your document

<head>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="js/bootstrap.js"></script>
</head>

一般来说,你的脚本会在文档的末尾靠近close主体标记和库等文库你正在使用去< head>

Generally your scripts go at the end of the document near the close body tag and libraries such as the ones you are using go at the <head>

这篇关于未捕获的ReferenceError:当jquery.js位于文档末尾时,未定义$的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆