При программировании в JavaScript, jQuery или Angular JS кодеры очень часто натыкаются на «Uncaught ReferenceError is not defined». Как правило, это происходит когда $, будь она переменной или методом, была задействована, но не была корректно определена. В сегодняшней статье мы посмотрим с вами на различные причины появления ошибки и методы их решения.
Содержание
- Uncaught ReferenceError is not defined — что это такое?
- Что вызывает появление ошибки
- 1. Библиотека jQuery была загружена некорректно
- 2. jQuery повреждена
- 3. jQuery не была загружена перед кодом JavaScript
- 4. Файл JqueryLibrary имеет атрибуты async или defer
- 5. Конфликт с другими библиотеками (prototype.js, MooTools или YUI)
- 6. Проблемы с плагином jQuery в WordPress
- Заключение
Uncaught ReferenceError is not defined — что это такое?
Как мы упомянули ранее, символ $ может использоваться для определения функции. Самая распространенная функция jQuery() называется $(document).ready(function()). Например
jQuery(“#name”).hide()
$(“#name”).hide()
Код выше применяется для скрытия элемента с помощью id=”name” через метод hide(). Во второй строчке вы можете видеть, что символ $ используется вместо метода jQuery().
Ошибка возникает тогда, когда вы пытаетесь получить доступ или использовать метод/переменную без символа $. При выполнении JavaScript в браузере перед пользователем вылетает ошибка, а все потому, что переменная не была определена (a variable being used is not defined). Вам необходимо задать переменную через var.
Вам также нужно определить функцию с помощью function() {}, чтобы избежать этой же ошибки.
Что вызывает появление ошибки
Давайте взглянем на другие причины появления рассматриваемой ошибки:
- Библиотека jQuery была загружена некорректно либо повреждена.
- Файл библиотеки jQuery был загружен после JavaScript.
- У библиотеки JavaScript имеются атрибуты async или defer.
- Конфликт с другими библиотеками, например, prototype.js, MooTools или YUI.
- Проблемы с плагином jQuery в WordPress.
1. Библиотека jQuery была загружена некорректно
Uncaught ReferenceError is not defined возникает в том случае, когда к методу jQuery был сделан запрос, но jQuery не была загружена на то время. Предположим, что вы работали без сети, но попытались загрузить или сослаться на код jQuery из Интернета, доступа к которому у вас нет, а следовательно jQuery не будет работать. Вы увидите ошибку, если исходник вашего кода находится на Google CDN, но последняя недоступна.
Лучшее решение в данном случае — это проверить сетевое подключение перед выполнением скрипта. Как альтернатива, вы можете загрузить файлы jQuery на свою систему и включить их непосредственно в сам скрипт. Для этого воспользуйтесь следующей строчкой:
<script src=”/js/jquery.min.js”></script>
2. jQuery повреждена
Если с файлом библиотеки jQuery наблюдаются какие-то проблемы, то, разумеется, появление ошибки неудивительно. Зачастую такая ситуация складывается тогда, когда пользователь загружает библиотеки из непроверенного источника. Возможно, на последнем jQuery выложена в уже поврежденном виде. Не экспериментируйте, а скачайте ее с официального сайта.
3. jQuery не была загружена перед кодом JavaScript
jQuery не была загружена перед скриптом. Если не сделать все как положено, скрипт, написанный в JavaScript, не будет работать — гарантированы постоянные ошибки.
Пример:
<html><head>
<script type=”text/javascript”>
$(document).ready(function () {
$(‘#clickme’).click(function(){
alert(“Link clicked”);
});
});
</script>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js” ></script>
</head>
<body>
<a href=”#” id=”clickme”>Click Here</a>
</body>
</html>
В этом коде jQuery загружен после скрипта. Так делать не нужно, а нужно вот так:
<html><head>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js” ></script>
<script type=”text/javascript”>
$(document).ready(function () {
$(‘#clickme’).click(function(){
alert(“Link clicked”);
});
});
</script>
</head><body>
<a href=”#” id=”clickme”>Click Here</a>
</body></html>
4. Файл JqueryLibrary имеет атрибуты async или defer
async — это булевый (логический) атрибут. При взаимодействии с атрибутом происходит загрузка скрипта с его последующим выполнением. Если парсер HTML не заблокирован во этого процесса, рендеринг странички будет ускорен.
Без атрибута async файлы JavaScript будут выполняется последовательно. Файлы JC будут загружены и запущены, затем начнется выполнение другого кода. В это время парсер HTML будет заблокирован и рендеринг веб-странички будет замедлен.
В случае атрибута defer скрипт будет выполнен после парсинга страницы. Это также булевый атрибут, который задействуется параллельно со внешними скриптами. Вот вам небольшой пример:
<!doctype html>
<html><head>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js” async defer></script>
<script type=”text/javascript”>
$(document).ready(function () {
$(‘#clickme’).click(function(){
alert(“Link clicked”);
});});
</script>
</head>
<body>
<a href=”#” id=”clickme”>Click Here</a>
</body>
</html>
Именно вышеуказанные атрибуты обеспечивают асинхронную загрузку библиотеки jQuery. Чтобы избежать появления Uncaught ReferenceError is not defined, нужно избавиться от атрибутов async и defer в скрипте.
5. Конфликт с другими библиотеками (prototype.js, MooTools или YUI)
Символ $ используется как шорткат для jQuery. Поэтому, если вы используете другие библиотеки JavaScript, которые задействуют переменные $, вы можете наткнуться на рассматриваемую ошибку. Чтобы исправить проблему, вам нужно перевести jQuery в неконфликтный режим после ее загрузки. Небольшой пример:
<!– Putting jQuery into no-conflict mode. –>
<script src=”prototype.js”></script>
<script src=”jquery.js”></script>
<script>
var $j = jQuery.noConflict();
// $j is now an alias to the jQuery function; creating the new alias is optional.
$j(document).ready(function() {
$j( “div” ).hide();
});
// The $ variable now has the prototype meaning, which is a shortcut for
// document.getElementById(). mainDiv below is a DOM element, not a jQuery object.
window.onload = function() {
var mainDiv = $( “main” );
}
</script>
В коде выше $ ссылается на свое оригинальное значение. Вы сможете использовать $j и название функции jQuery.
Но есть еще одно решение! Вы можете добавить этот код в шапку своей странички индекса:
<script>
$=jQuery;
</script>
Корректный код:
<!doctype html>
<html><head>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js”></script>
<script type=”text/javascript”>
$(document).ready(function () {
$(‘#clickme’).click(function(){
alert(“Link clicked”);
});
});
</script>
</head>
<body>
<a href=”#” id=”clickme”>Click Here</a>
</body>
</html>
6. Проблемы с плагином jQuery в WordPress
Uncaught ReferenceError is not defined — настоящий кошмар для веб-разработчиков, использующих jQuery в WordPress. Появление ошибки способно полностью вывести из строя сайт. Главная причина — это конфликт между двумя или более плагинами jQuery. Например, есть старая версия плагина на jQuery, у которого $ — его имя, и какой-то сторонний плагин, который не использует $ в качестве шортката для jQuery и может иметь совершенно другое значение.
И вот из-за такой разницы и получается конфликт. Два значения $, отвечающих за совершенно разные вещи, не могут сосуществовать в одной программе. Вы гарантированно получите ошибку.
Решение:
- Убедитесь, что библиотека jQuery загружена перед JavaScript. Плюс постарайтесь использовать наиболее актуальную версию jQuery.
- Библиотека jQuery уже доступна в WordPress, так что вам не нужно прикладывать ее с помощью CDN/URL. Вы можете использовать функцию wp_enqueue_script(), чтобы включить jQuery в ваш файл.
Заключение
Появления Uncaught ReferenceError is not defined можно избежать, если придерживаться всего, что мы указали выше. Еще одна причина появления ошибки — это неправильно указанный путь к jQuery. Возможно, в расположении файла где-то есть опечатка либо сам файл был перемещен/удален из своей оригинальной директории. Если же используете онлайн-версию библиотеки, убедитесь, что с вашим сетевым подключением все в порядке.
Quick Solutions To Uncaught ReferenceError: $ is not defined jQuery Error. Understanding reasons and applicable common solutions to any javascript frameworks.
1. Overview
In this tutorial, We will be discussing how to solve the famous jQuery error «Uncaught ReferenceError: $ is not defined jQuery Error» that occurs for every developer who started working on jQuery API.
More on JQuery
This error comes into existence if you are trying to use a $ variable that is not defined yet using the var keyword. In jQuery world, it’s a short name of jQuery() function and most commonly used in $(document).ready(function()). When dom is loaded, you are making some stuff using jQuery then there might be chances of corrupting the jQuery library or jQuery file location. This indicates with an error saying «uncaught reference error $ is not defined». This is the most generic error even if you are working on Angular Js, Ajax, Html, and MVC, laravel or rails .. any framework that is related to javascript. Because all of these are built on top of JavaScript.
In my experience, I have seen the junior developers or whose background is java, .Net, C#, Android technologies, and these developers is not having enough knowledge of JavaScript. JavaScript understanding is a must to work on jQuery or any JavaScript framework such as Angular, React or vue.js or ember.js. Once you know the basic concepts of JavaScript, you can troubleshoot any problems easily.
Let us start now on how to fix this common error.
2. Solution 1: Using before defining — Uncaught ReferenceError: $ is not defined
Case: Invoking the function or using a variable before declaring it.
As you are aware, all javascript code is executed inside the browser such as Chrome, Mozilla, Safari, and IE. So, If you use any variable before declaring or defining, browse will throw this error.
Let us take an example code that throws the error.
value; // ReferenceError: value is not defined var value; value; // No more errors here. Becuse value is defined before its usage.
In the first line, the variable value is not defined at this time. So, the browser will show the error. But, once you define and use it, it will not show any errors.
The same logic is applied to the methods as well.
execute(); // ReferenceError: execute is not defined execute() = function() { // some code } execute(); // no errors.
3. Solution 2: Loading child scripts before loading parent scripts
For example, for all jQuery applications, jquery-3.4.1.min.js is the parent file and other jQuery plug-in scripts will be child scripts.
See the below wrong usage that produces Uncaught ReferenceError: $ is not defined jQuery Error.
<script src="http://code.jquery.com/jquery-plugins.js"></script> <script src="http://code.jquery.com/jquery-3.4.1.min.js"></script>
Here is the order of scripts causing the problem. jquery-plugins.js is developed by using a jquery-3.4.1.min.js script. But, we are trying to load the plugins jquery-plugins.js script first then next load the core jquery-3.4.1.min.js scripts.
To avoid the error, we should load the scripts in proper order as below.
<script src="http://code.jquery.com/jquery-3.4.1.min.js"></script> <script src="http://code.jquery.com/jquery-plugins.js"></script>
Another set of correct loading scripts.
<script src="http://code.jquery.com/jquery-3.4.1.min.js"></script> <script src="http://code.jquery.com/ui/1.12.1/jquery-ui.min.js"> </script>
Note: All parent scripts must be executed before child scripts execution.
4. Solution 3: Checking Internet Connectivity for Remote Files
Some of the applications do not load the jQuery core files from their own file system. Instead, they use Google CDN or Microsoft CDN files which are stored and distributed in remote locations. The below script file is loaded remotely.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script>
Now, Trying to do the below jquery operation. If the application is accessed from no network area then it will fail to load the jQuery core script and run our code below. So, it cannot ‘$’ the variable and throw the error.
$("#section1").hide()
Now, to fix this problem either we should have the internet or should have the file offline. Download the script and save it to the file system. Finally, use it as below.
<script src="../lib/jquery.min.js"></script>
5. Solution 4: Incorrect Script Location
This is the most common mistake done by the newbies. If you are already using CDN file or local files and later files names were renamed to new. So, the files that are being used now are no more exists. So we need to update the file names to right one.
Another mistake is the incorrect file location. If you are not providing the full path or relative path appropriately.
And last but not least, spelling mistakes in the file names.
6. Conclusion
In this article, We’ve seen all possible error scenarios and solutions to Uncaught ReferenceError: $ is not defined jQuery Error.
Ref 1
Ref 2
While programming in JavaScript, jQuery or Angular JS, coders often encounter an error called Uncaught ReferenceError: $ is not defined. This usually happens when the $, that may be a variable or a method is not properly defined but is being used.
In this article, we will look at the various reasons why this error occurs and the ways to solve it.
But first, let us find out a little more about this error.
Uncaught ReferenceError: $ is not defined error: What is it?
As mentioned earlier, the $ symbol is used to represent a function, that is the most common jQuery() function called $(document).ready(function()). For example,
jQuery("#name").hide()
$("#name").hide()
The code written here is used for hiding the element with the id=”name” using the hide() method. In the second line, you can see that the $ symbol is used in place of the jQuery() method.
But the error is encountered when you are trying to access or use a method or variable not declared using the $ symbol. As JavaScript runs inside a browser, it throws an error when a variable being used is not defined. You have to declare a variable using the var keyword.
Similarly, you need to define a function using the function() {} keyword to avoid this error.
Causes of Error
Now let us look at the other causes of the Uncaught References error:
- Jquery library not loaded properly
- The jQuery library file is corrupted
- jQuery library file not loaded before JavaScript code
- Jquery library file has async or defer attribute
- Conflict with other libraries like (prototype.js, MooTools, or YUI)
- jQuery plug-in Issue in WordPress
1) Jquery Library not Loaded Properly
The error may happen when a call is made to a jQuery method, but jQuery is not loaded at that time. There may be a case where you might be working offline. But you are loading or referring the jQuery code from the internet, and there is a problem with the connection, jQuery will not work. If the code is being sourced from Google CDN, but it is not accessible, the error occurs.
The best solution to this problem is to check internet connectivity before running your script. Alternatively, you can download the jQuery files on your system and include them inside your script. Use the code below to use jQuery:
<script src="/js/jquery.min.js"></script>
2) The jQuery Library File is Corrupted
The Uncaught error may also arise if there is a problem in the jQuery file. If the jQuery library file has been downloaded from untrustworthy sites and the file is corrupted, this may happen.
3) jQuery Library File Not Loaded Before JavaScript Code
Another important reason for this error is that you are not loading jQuery before your script. If you do this, the code written in JavaScript will not work and will result in the error.
Example:
<html><head>
<script type="text/javascript">
$(document).ready(function () {
$('#clickme').click(function(){
alert("Link clicked");
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" ></script>
</head>
<body>
<a href="#" id="clickme">Click Here</a>
</body>
</html>
In this code, you can see that the jQuery is loaded after the script. To fix this, include the jQuery library file inside the head section of the HTML file, before the JavaScript code. Do the following:
<html><head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function () {
$('#clickme').click(function(){
alert("Link clicked");
});
});
</script>
</head><body>
<a href="#" id="clickme">Click Here</a>
</body></html>
4) JqueryLibrary File has Async or Defer Attribute
The async is a Boolean attribute. This specifies that the scripts will be downloaded as and when they are encountered. Then they will be executed when the downloading is completely finished. As the HTML parser is not blocked during this process, the pages are rendered faster.
Without this attribute, the JavaScript files are run sequentially. So, the JS file gets downloaded and executed, then the other code will run. During this time, the HTML parser will be blocked, so pages will be rendered slower.
In case of the defer attribute, the script will be run after the page has been parsed. This is also a Boolean attribute that is used along with external scripts. For example,
<!doctype html>
<html><head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" async defer></script>
<script type="text/javascript">
$(document).ready(function () {
$('#clickme').click(function(){
alert("Link clicked");
});
});
</script>
</head>
<body>
<a href="#" id="clickme">Click Here</a>
</body>
</html>
Because these attributes make jQuery library file load in asynchronous mode. The best way to avoid the Uncaught Error, in this case, is to remove the async and defer attribute.
5) Conflict with Other Libraries Like (prototype.js, MooTools, or YUI)
jQuery uses $ as a shortcut for jQuery. Thus, if you are using another JavaScript library that uses the $ variable, you can run into conflicts with jQuery.
To fix this issue, you need to put jQuery into no-conflict mode, after it is loaded. For example,
<!-- Putting jQuery into no-conflict mode. -->
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
var $j = jQuery.noConflict();
// $j is now an alias to the jQuery function; creating the new alias is optional.
$j(document).ready(function() {
$j( "div" ).hide();
});
// The $ variable now has the prototype meaning, which is a shortcut for
// document.getElementById(). mainDiv below is a DOM element, not a jQuery object.
window.onload = function() {
var mainDiv = $( "main" );
}
</script>
In the code written above, the $ will refer to its original meaning. You will be able to use the alias $j and the function name jQuery.
There is another solution, you can add this code at the top of your index page:
<script>
$=jQuery;
</script>
Correct Code
<!doctype html>
<html><head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#clickme').click(function(){
alert("Link clicked");
});
});
</script>
</head>
<body>
<a href="#" id="clickme">Click Here</a>
</body>
</html>
6) jQuery plug-in Issue in WordPress
While using jQuery with WordPress, the Uncaught ReferenceError: jQuery is not definedis a very common error. This error may shut down your WordPress website. So, this error is a nightmare for web developers.
There are a few reasons for this error. Out of them the most common reasons is when two or more jQuery plug-ins conflict against each other. For example, an old plug-in written in jQuery might have the symbol $ representing its own name. But in another third-party plug-in, the $ symbol might not be used as a shortcut for jQuery and can have another value.
As both values of $ cannot exist in the same program at the same time, the Uncaught Error is encountered.
Solution:
- To avoid this make sure that jQuery library loaded before JavaScript. Also, make sure that the latest version of jQuery is loaded on your system
- The jQuery library is already available in WordPress so you do not have to include it using a CDN or hosted URL. You can use the wp_enqueue_script() function to include jQuery in your file
Conclusion:
The Uncaught ReferenceError: $ is not defined can be avoided if you keep in mind the points mentioned above. Another reason for the error is when the jQuery path which you have provided is incorrect. There may be a typo in the path, or the file could have been removed from the location you specified. So, make sure your jQuery files are in place. And if you are using the online version, check whether the internet is working to avoid any issues.
If you are using jQuery, Angular JS, or plain old JavaScript and getting «Uncaught ReferenceError: $ is not defined» error which means $ is either a variable or a method that you are trying to use before declaring it using the var keyword. In jQuery, it’s a short name of jQuery() function and most commonly used in $(document).ready(function()). If you are doing some jQuery stuff when DOM is loaded and getting this error it means your browser has a problem loading jQuery library either from the internet or local file system.
In this article, you will see some of the most common reasons for «Uncaught ReferenceError: $ is not defined» errors and how to solve them, but before that let’s learn some basics about the dreaded Uncaught ReferenceError: $ is not defined error.
And, If you want to learn Modern JavaScript or level up your skills then I suggest you join these best JavaScript online courses. It’s one of the best and hands-on courses to learn ES 6 and other new Javascript features.
One of the common reasons for such error is directly starting with jQuery without knowing JavaScript fundamentals. I have seen many web developers who come from Java, C#, HTML, and Python backgrounds started using jQuery without knowing much about JavaScript.
If you happen to work on the same scenario, I strongly suggest you read at least one of the good JavaScript books for beginners like Head First JavaScript. Always remember that jQuery is a library built on JavaScript, once you know JavaScript, it’s much easier to troubleshoot any jQuery error.
Uncaught ReferenceError: X is not defined
Since JavaScript executes inside the browser, your browser like Firefox, Chrome, Edge, or Internet Explorer throws this error when you are using a variable that is not defined, for example, the following code will throw this error, but once you declare the variable using the var keyword, the error will go away:
data; // ReferenceError: data is not defined var data; data; // No more errors
Similarly, if you access a method before declaring it you will get this error as shown below:
process(); // ReferenceError : process is not defined process = function(){}; process(); // No errors
Now that you have learned when does browser throws Uncaught ReferenceError: $ is not defined, it’s time to look at some common reasons this error occurs while using jQuery, AngularJS or other JavaScript library which uses $ as a shortcut.
1) One of the most common reason of «ReferenceError: $ is not defined» in jQuery based application is that jQuery plugin is included before jQuery file. Since jQuery plugin uses $, it throw «ReferenceError: $ is not defined» if it doesn’t find, which is logical because jQuery was not loaded until then.
<script src="/lib/jquery.plugin.js"></script> <script src="/lib/jquery.min.js"></script>
Solution: Include the jquery.js file before any jQuery plugin files.
<script src="/lib/jquery.min.js"></script> <script src="/lib/jquery.plugin.js"></script>
2) The second most common reason of getting «ReferenceError: $ is not defined» in jQuery is due to the incorrect path, either it’s a typo or jQuery file is moved to some other location, the browser is not able to load the jQuery file.
One solution of this problem is simply to fix the path to jQuery library. If you are downloading jQuery from CDN then you can also use Google hosted jQuery file, which is almost always available.
3) Another bizarre but a common reason of «ReferenceError: $ is not defined» in jQuery» is that you might be working offline but loading jQuery from internet. It’s one of the silly mistake every web
developer makes it sometime or other. Solution is simple, either connect to internet or use a local copy of jQuery library as shown below:
<script src="/js/jquery.min.js"></script>
That’s all about how to fix the «Uncaught ReferenceError: $ is not defined» in jQuery. You can follow similar approach to any other JavaScript library which is using $ as shortcut. Most of the cases mentioned here also applicable to common libraries like AngularJS and others as well.
Thanks for reading this article so far. If you like this article then please share with your friends and colleagues. If you have any question or doubt then please drop a comment.
Disclosure: This article may contain affiliate links. When you purchase, we may earn a commission.
Hello JavaScript developer, if you are wondering how to fix the Reference Error $ is not defined while using jQuery then you have come to the right place. «Reference Error: $ is not defined» is one of the common JavaScript errors which come when you try to use $, which is a shortcut of jQuery() function before you load the jQuery library like calling $(document).ready() function. «ReferenceError: XXX is not defined» is a standard JavaScript error, which comes when you try to access a variable or function before declaring it. Since jQuery is also a JavaScript library, you must first include the declaration of the jQuery function or $() before you use it.
In order to understand this error more, let’s see how to reproduce «Reference Error: $ is not defined» in JavaScript with simple examples of «reference error: jQuery is not defined»
Here is an example of Reference Error: not defined in JavaScript for both variable and function as this can come for both while accessing an undefined variable or calling an undefined function in JavaScript.
// accessing function without defining it getCount(); // ReferenceError: getCount is not defined getCount = function(){}; getCount() // No errors
It’s clear now that «Uncaught ReferenceError: XX is not defined» comes when you try to access XX, which could be a variable or function before defining it.
And, If you want to learn Modern JavaScript or level up your skills then I suggest you join these free JavaScript courses online. It’s one of the best and hands-on courses to learn ES 6 and other new JavaScript features.
5 Common Reasons ReferenceError: $ is not defined in jQuery
Having said that, let’s see some common scenarios or mistakes which cause the «Uncaught ReferenceError: $ is not defined» error while using jQuery in your project:
1. Path to your jquery.js file is wrong and it can not be found (Error 404).
This problem can be solved by fixing your path to the jquery.js file. If your project is a public website, you better use Google hosted jQuery files to avoid such issues.
2. jQuery plugin is included before the jQuery file.
You can solve this problem by including jquery.js file before any jQuery plugin files.
3. jQuery UI is included before jQuery min library
You cannot put the script reference to jquery-ui before the jQuery script itself. That’s what fixed the problem to me: first jquery-x.x.x.min.js, then jquery-ui-xxxxxx.js
4. You are including the jQuery file without the protocol in the URL and accessing the page from your local file system. This is a silly mistake but it happens. To solve this problem just add HTTP protocol (http:// instead of //) in the URL while you are developing.
Sometimes this error also comes «jQuery not defined» as shown below:
5. jQuery file is included from the web, but you don’t have an internet connection. It is a silly mistake, but you would be surprised how often it happens. You can solve this problem by including a local jquery.js file copy or connect to the internet
6. Incorrect order of script while loading multiple JavaScript files
If you are loading multiple JavaScript files using the script tag, you must first load jQuery one. corrected it
That’s all about the common reasons for Reference Error: $ is not defined in jQuery. Most likely your problem should be solved by following these tips. If the above cases do not solve your case, try to figure out why jQuery is not loaded before the line where this error is thrown.
Related jQuery tutorials you may like
- How to get the current URL, Parameters, and Hash using jQuery? (solution)
- 5 Free Courses to learn jQuery for beginners (free courses)
- How to use more than one jQuery UI Date Picker in the JSP page? (example)
- 10 Free Courses to learn JavaScript for beginners (free courses)
- How to create tab-based UI using jQuery? (example)
- 10 Free courses to learn Angular for beginners (free courses)
- How to redirect a page URL using jQuery and JavaScript? (solution)
- Top 5 Websites to learn JavaScript for FREE (websites)
- How to write HelloWorld in jQuery? (solution)
- 5 Books to learn jQuery for Web developers (books)
- Top 10 Courses to learn JavaScript tin depth (best courses)
- How to load jQuery on a web page? (solution)
- Difference between jQuery document.ready() and JavaScript window.onload event? (answer)
Thanks for reading this article so far. If you find this article useful then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.
P. S. — If you want to become a web developer, you can also see these free web development courses to find out which frameworks, libraries, tools, and technologies you need to learn to become the Web developer you always wanted to be.