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>
If I move the Jquery link to the header, then the code runs fine, but this will slow the page loading time.
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?
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>
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>
I like keeping jquery at the bottom, you'll just need to make sure the entire DOM is loaded first, and to check that without jQuery as that's not usable yet. Try using this instead:
document.addEventListener("DOMContentLoaded", function(event) { $(function(){ $('#example').popover({ trigger:'hover' }); }); });
You need to include jQuery before referencing the jQuery library.
Change to this:
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<script type="text/javascript">
$(function(){
$('#example').popover({ trigger:'hover' });
});
</script>
Also note that it is a good idea to include jQuery and other JavaScript in the footer of your document to ensure that page rendering is not delayed.
Recently on jsTree site I've seen another technique
at the top (in the HEAD tag) you set just this:
<script>window.$q=[];window.$=window.jQuery=function(a){window.$q.push(a);};</script>
Now you can do <script>$(function () { /* your $() calls here */ });</script>
whenever and wherever you want...
at the end include jquery.js as usal and then the last script is:
<script>$.each($q,function(i,f){$(f)});$q=null;</script>
hope this is usefull to someone...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With