So classic problem, but having a horrible time on finding the actual cause. Typically when I see this error it’s because the jQuery reference is after code requiring it, or back jQuery link, or jQuery conflict, etc… so far none of those appear to be the case. Unfortunately seeking out the solution to this problem has lead me to post after post of such cases. I’m sure my problem here is equally as simple, but over an hour of hunting, still no luck…
Edit: Additional information…
The solution file (which I’ve recreated multiple times trying to figure this out. Is a JavaScript Windows Store Blank App template and I’m doing this in Visual studio. The only references files is Windows Library for javascript 1.0, I have tried deleting this to test as well.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>HTML5 Canvas Template</title>
<style>
/* styles here */
</style>
</head>
<body>
<canvas id="myCanvas" width="500" height="500">
<p>Canvas not supported.</p>
</canvas>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var canvas = $("#myCanvas").get(0);
var context = canvas.getContext("2d");
function renderContent()
{
// we'll do our drawing here...
}
renderContent();
});
</script>
</body>
</html>
asked Feb 20, 2013 at 2:38
Eric J FisherEric J Fisher
3241 gold badge6 silver badges14 bronze badges
5
It’s states that JQuery referred URL is not correct
Try this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
samayo
16.1k12 gold badges89 silver badges105 bronze badges
answered Feb 20, 2013 at 2:49
codercoder
13k31 gold badges110 silver badges213 bronze badges
8
I tried everything listed above and nothing seems to work until I put this string
<script src="../scripts/jquery-2.2.3.min.js" type="text/javascript"></script>
in the head section of the HTML file. So here’s how it looks:
<!DOCTYPE html>
<html>
<head>
<!-- jQuery Reference -->
<script src="../scripts/jquery-2.2.3.min.js" type="text/javascript"></script>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<title>some title</title>
</head>
<body>
...
And the js file is located at a level below in the folder ‘scripts’.
Finally, the error is gone and what a relief!
answered May 4, 2016 at 18:09
3
In my case, the problem was that I was rendering my page over https but I was trying to request the JQuery file over http, which is blocked by many browsers for security reasons.
My fix was to change this…
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
…to this…
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
This causes the browser to download JQuery using the same protocol (http or https) as the page being rendered.
answered Jul 27, 2015 at 22:51
Chris GillumChris Gillum
14.4k5 gold badges47 silver badges60 bronze badges
Some of my clients had this problem, because apparently they blocked loading Javascript from 3rd party sites. So now I always use the following code to include jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
window.jQuery ||
document.write('<script type="text/javascript" src="/js/jquery-1.9.1.min.js">x3C/script>')
</script>
This makes sure, that even if my client blocks loading the Javascript file from the CDN domain, the client still downloads the file from my own server, which is not blocked by the browser.
answered Jan 6, 2016 at 1:22
Pascal KleinPascal Klein
23.4k24 gold badges82 silver badges119 bronze badges
Anover variant, in my case — I was forced to use proxy. So — IE11—> InternetOptions —> Connections—>LANSettings-Proxy Server—> UseProxyServer — should be checked.
Also check awailability of jQUery script source, my worked variant in VS2012 — -just like in top example
Rajesh
10.3k15 gold badges43 silver badges64 bronze badges
answered Jul 3, 2014 at 10:22
I was getting this same error code:
(Error: ‘generateText’ is undefined)
…on the code
var bodyText=["The....now."]
I discovered on my text-editor(Notepad++), when typing many lines of text in the directly above the variable bodyText, if I didn’t hit return carriage (enter==>WordWrap is off) just kept typing w/o return carriage and let the editor adjust text it worked?
Must be in the settings of Notepad++??
CodeMouse92
6,80814 gold badges72 silver badges130 bronze badges
answered Apr 27, 2016 at 21:43
I had similar issue. My test server was working fine with «http». However it failed in production which had SSL.
Thus in production, I added «HTPPS» instead of «HTTP» and in test, i kept as it is «HTTP».
Test:
wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', array(), null, false );
wp_register_script( 'custom-script', plugins_url( '/js/custom.js', __FILE__ ), array( 'jquery' ) );
Production:
wp_register_script( 'jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', array(), null, false );
wp_register_script( 'custom-script', plugins_url( '/js/custom.js', __FILE__ ), array( 'jquery' ) );
Hope this will help someone who is working on wordpress.
При программировании в 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. Возможно, в расположении файла где-то есть опечатка либо сам файл был перемещен/удален из своей оригинальной директории. Если же используете онлайн-версию библиотеки, убедитесь, что с вашим сетевым подключением все в порядке.
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.
СсылкаОшибка:»x» не определено
Исключение JavaScript « переменная не определена» возникает, когда где-то есть ссылка на несуществующую переменную.
Message
ReferenceError: "x" is not defined (V8-based & Firefox) ReferenceError: Can
Error type
Что пошло не так?
Где-то есть ссылка на несуществующую переменную. Эта переменная должна быть объявлена или вам нужно убедиться, что она доступна в вашем текущем скрипте или области .
Примечание. При загрузке библиотеки (например, jQuery) убедитесь, что она загружена, прежде чем обращаться к переменным библиотеки, таким как «$». Поместите элемент <script> , загружающий библиотеку, перед кодом, который его использует.
Examples
Переменная не объявлена
Переменная «foo» нигде не определена. Это должна быть какая-то строка, чтобы метод String.prototype.substring() работал.
const foo = 'bar'; foo.substring(1);
Wrong scope
Переменная должна быть доступна в текущем контексте выполнения. Переменные, определенные внутри функции, не могут быть доступны из любого места за пределами функции, потому что переменная определяется только в области видимости функции.
function numbers() { const num1 = 2; const num2 = 3; return num1 + num2; } console.log(num1);
Однако функция может получить доступ ко всем переменным и функциям,определенным в области видимости,в которой она определена.Другими словами,функция,определенная в глобальной области видимости,может получить доступ ко всем переменным,определенным в глобальной области видимости.
const num1 = 2; const num2 = 3; function numbers() { return num1 + num2; } console.log(numbers());
See also
- Scope
- Объявление переменных в Руководстве по JavaScript
- Область функций в руководстве по JavaScript
JavaScript
-
TypeError: «x» не является конструктором
Исключение JavaScript «не является конструктором» возникает, когда была попытка использовать объектную переменную, но была попытка использовать объект или переменную
-
TypeError: «x» не является функцией
Исключение JavaScript «не является функцией» возникает, когда была попытка вызвать значение из, но на самом деле оно попыталось вызвать значение из функции, но
-
RangeError:точность вне досягаемости
Исключение JavaScript «точность вне допустимого диапазона» возникает, когда число, выходящее за пределы 0 и 20 (или 21), было передано в toFixed toPrecision.
-
Ошибка: Отказано в доступе к свойству «x»
Исключение JavaScript «Отказано в доступе к свойству» возникает, когда был объект попытки, для которого у вас нет исключения DOMException.


