How to Fix "$ is not defined" Errors in JavaScript
If you are getting "Uncaught ReferenceError: $ is not defined" errors in JavaScript, it means you most likely want to use jQuery, but jQuery is not defined in your page. This mostly happens because the library is getting loaded only after you already use jQuery. Take a look at the following example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>jQuery - Uncaught ReferenceError: $ is not defined</title>
</head>
<body>
<script>
$('button').click(() => {
console.log('jQuery is ready π')
})
</script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous">
</script>
</body>
</html>
Here, we reference a jQuery object, but since we load the jQuery library only after using jQuery-specific code, we get the above error. Therefore, this won't work.
How to Fix the Error
In order to fix the error, we need to switch the order. Make sure you include your jQuery library as the first thing in your app, and you only reference it once it is loaded.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>jQuery - Uncaught ReferenceError: $ is not defined</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous">
</script>
<script>
$('button').click(() => {
console.log('jQuery is ready')
})
</script>
</body>
</html>
Notice that you want to load scripts as the last thing in your body, or use async
or defer
.
We can also add a simple check to verify if jQuery is already present on the page or note. This way, you can ensure that your jQuery-specific code will only run if jQuery is indeed present on the page.
if (typeof $ !== 'undefined') {
// jQuery specific code goes here
}
You can use the typeof
operator to check the type of a variable.
Lastly, whenever you are working with jQuery, make sure you wait for the document.ready
event before you execute any code. You can do this in the following way:
$(document).ready(function() {
// The document is now ready here
})

Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: