Uncaught referenceerror jquery is not defined как исправить

When you want to build a microsite, jQuery can help you simplify client side interactivity. If you build your website with WordPress, then you will be able to use jQuery in the custom theme that yo…

When you want to build a microsite, jQuery can help you simplify client side interactivity. If you build your website with WordPress, then you will be able to use jQuery in the custom theme that you are building.

Since you will base your site interactivity on jQuery, you may write JavaScript codes that throw the following error:

Uncaught ReferenceError: jQuery / $ is not defined.

In some cases, the error may appear randomly, making it hard to detect.

So how can we prevent our JavaScript codes from throwing a «Uncaught ReferenceError: jQuery / $ is not defined»?

In order to prevent our JavaScript codes from throwing a «Uncaught ReferenceError: jQuery / $ is not defined», we need to ensure that the jQuery library:

  1. is available for the browser to download.
  2. is loaded before any of our JavaScript codes uses $ or jQuery

1. Making sure that the jQuery library is available for the browser to download

First of all, we need to ensure that the URL to a copy of jQuery library valid.

If you are using Chrome, then you can use the developer tool to check if the URL is valid.

When the URL to a copy of jQuery library is invalid, you should find a 404 error in the console.

So how do you get to the console?

In order to do so, right-click on your web page and choose Inspect.

After the chrome developer tool is loaded, click on the cross icon:
chrome developer tool with 2 errors

When you have done so, you should be able to see a 404 being reported in the console.
chrome developer console showing 404 (Not Found) to jQuery library

As shown above, the browser is not able to get ajquery-3.5.1.slim.min.js from the server. In this case, we had accidentally typed an extra a in front of the file name.

When that happens, any usage of the $ variable will report a «Uncaught ReferenceError: $ is not defined».

In case you are wondering, these are the HTML and JavaScript codes that caused the errors:

<html>
<head>
    <title>Saying hello</title>
</head>
<body>
    <script src="https://code.jquery.com/ajquery-3.5.1.slim.min.js"></script>
    <script>
        $(document).ready(function() {
            alert('Hello there');
        });
    </script>
</body>
</html>

Even though the URL can be a valid link to a jQuery library, the browser may fail to retrieve it because the server is down.

In order to ensure that the browser loading your codes can load a jQuery library, you can:

  1. Host the jQuery library on the HTTP server / reverse proxy server that serves your JavaScript codes. If your server is unavailable, then your JavaScript codes will not run anyway.
  2. Get a copy of jQuery from one of the Content Delivery Networks that host jQuery libraries. For example, you can link to a copy of jQuery from jQuery CDN, Google Hosted Libraries or cdnjs. One advantage of using a popular CDN is that your website visitor may have already downloaded the jQuery library that your codes references. When that happens, the jQuery library is fetched from the browser’s cache directly. In addition to that, even if a download is needed, the CDN will direct the browser to the nearest server. Therefore the jQuery library can be loaded in the shortest possible time.

2. Making sure that the jQuery library is loaded before any of your JavaScript codes uses $ or jQuery

If you can control the inclusion of jQuery library on your web page, the most straightforward way is to tell the browser to download jQuery library before running our JavaScript codes:

<html>
<head>
    <title>Saying hello</title>
</head>
<body>
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script>
        $(document).ready(function() {
            alert('Hello there');
        });
    </script>
</body>
</html>

As shown above, the inline JavaScript will not run until the browser finish loading and running jquery-3.5.1.slim.min.js. Therefore, the reference to the $ variable will always be valid if the server at code.jquery.com is able to return jquery-3.5.1.slim.min.js in a HTTP response.

But what if you have no control to where your JavaScript codes is placed or how the script element to the jQuery library is written?

For example, the following code tell the browser to load the jQuery library asynchronously:

<html>
<head>
    <title>Saying hello</title>
</head>
<body>
    <script async src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script>
        $(document).ready(function() {
            alert('Hello there');
        });
    </script>
</body>
</html>

When the browser sees the above HTML file, it will download jquery-3.5.1.slim.min.js without blocking the parser. Therefore, the $ variable can be referenced before the jQuery library is being loaded by the browser. When that happens, you will not be able to see the alert popup.

If there are lots of codes in between the two script elements, then the error may not be apparent.

So how can we make sure that the jQuery library is loaded before any of our JavaScript codes uses $ or jQuery variable?

In order to do so, we can test whether window.jQuery is defined before referencing the $ or jQuery variable. If window.jQuery is not defined yet, then we wait for some time before checking again.

When window.jQuery is defined, we can then run our JavaScript codes that references the $ or jQuery variable.

Given that, we can rewrite our example as follows:

<html>
<head>
    <title>Saying hello</title>
</head>
<body>
    <script async src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script>
        function run() {
            if (window.jQuery) {
                $(document).ready(function() {
                    alert('Hello there');
                });
            }
            else {
                setTimeout(run, 50);
            }
        }
        run();
    </script>
</body>
</html>

After the code change, we can be sure that usage of the $ variable only happens after the browser loads the jQuery library.

beget banner 468x60beget banner 728x90beget banner 930x180jivo banner 468x60jivo banner 728x90jivo banner 930x180flexbe banner 468x60flexbe banner 728x90flexbe banner 930x180

Наиболее распространенной причиной ошибки «Uncaught ReferenceError: $ is not defined» является выполнение кода jQuery до загрузки файла библиотеки jQuery. Поэтому убедитесь, что вы выполняете код jQuery только после завершения загрузки файла библиотеки jQuery.

Также, если вы динамически подключаете файл библиотеки jQuery, проверьте исходный код страницы с помощью инструмента разработчика браузера, чтобы убедиться, что он включен правильно и в нужном месте.

Давайте посмотрим на следующий пример, чтобы понять, как это работает:

<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery - $ is not defined</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        alert("jQuery работает отлично");
    });      
});
</script>
</head>
<body>
    <button type="button">Test jQuery Code</button>
</body>
</html>

Если вы все еще получаете эту ошибку, могут быть другие причины, например, если у вас есть локальная копия файла библиотеки jQuery, она может быть отредактирована или повреждена. Загрузите новую копию файла библиотеки jQuery с официального сайта или используйте ссылку CDN, как мы использовали в приведенном выше примере.

Читайте также

Похожие посты

Вы можете просто использовать JavaScript-метод location.reload() для обновления или перезагрузки страницы. Этот метод дополнительно принимает логический параметр true или false. Если указан параметр true, это вызывает постоянную перезагрузку страницы с сервера. Но, если установлен false (по умолчанию) или не указан, браузер может перезагрузить страницу из своего кеша. Давайте посмотрим на пример, чтобы понять, как работает…

Вы можете использовать jQuery-метод css(), чтобы изменить значение свойства CSS display на none, block или любое другое значение. Метод css() применяет правила стиля непосредственно к элементам, то есть к встроенным. Следующий пример изменит отображение элемента DIV при нажатии кнопки: В качестве альтернативы, если вы беспокоитесь о начальном значении свойства display элемента, но хотите переключаться между…

В следующем примере показано, как отображать и скрывать элементы <div> на основе раскрывающегося списка или выбранного параметра в поле <select> с помощью jQuery-метода change() в сочетании с методами show() и hide(). Блоки <div> в этом примере по умолчанию скрыты с помощью CSS-свойства display, для которого установлено значение none.

$ is not defined в jQuery: что это значит и что делать

Новая рубрика — «Типичные ошибки». Будем разбираться, что означают разные ошибки в программах и как с ними быть.

Новая рубрика — «Типичные ошибки». Будем разбираться, что означают разные ошибки в программах и как с ними быть.

Где можно встретить $ is not defined и что это значит

Скорее всего, эту ошибку вы встретите в сообщениях консоли браузера, когда будете подключать к своему сайту какую-нибудь JavaScript-библиотеку, которая использует jQuery. Например, это может быть листалка фотографий или форма обратной связи.

$ is not defined означает, что на момент, когда ваша библиотека пыталась сделать что-то с помощью jQuery, сама jQuery либо не была загружена, либо загрузилась некорректно.

Что делать с ошибкой $ is not defined

Сделайте так, чтобы сначала у вас корректно загружалась jQuery, и только потом — остальной код, который использует эту библиотеку. Обычно для этого достаточно поставить вызов jQuery раньше всех других вызовов.

Было:
<script src="ВАШ СКРИПТ"></script>
<script src="https://yastatic.net/jquery/3.3.1/jquery.min.js"></script>

Стало:
<script src="https://yastatic.net/jquery/3.3.1/jquery.min.js"></script>
<script src="ВАШ СКРИПТ"></script>

Если перемещение вызова jQuery не помогло

Проверьте, откуда вы берёте библиотеку jQuery. Может быть, вы берёте её с удалённого сайта, до которого ваш браузер не может дозвониться (Роскомнадзор постарался или просто сайт лежит). Тогда скачайте jQuery на компьютер и вызовите локально:

<script src="script/jquery.min.js"></script> <!--при этом не забудьте скачать и положить сюда библиотеку jQuery-->

<script src="ВАШ СКРИПТ"></script>

Простой способ убедиться, что jQuery загружается нормально, — скопировать её адрес из кода и вставить в адресную строку браузера. Если вам выведется программный код, значит, jQuery вам доступна и загружается. Если что-то пойдёт не так — вы увидите это на экране.

Например, попробуйте перейти по этой ссылке: https://yastatic.net/jquery/3.3.1/jquery.min.js — если она у вас открывается и вы видите месиво из кода, значит, jQuery для вас открылась.

Знак $ в JavaScript — это название сущности, через которую мы делаем всевозможные запросы с помощью jQuery.

jQuery — это дополнительная библиотека, которая упрощает работу с элементами на веб-странице. Например, если нам нужно с помощью JavaScript на лету поменять какую-то надпись на странице, то без jQuery нам бы пришлось сделать так:

document.getElementById('someElement').innerHTML='Some New Text';

А через jQuery всё то же самое делается так:

$("#someElement").html("Some New Text");

Знак доллара при отладке JS (то есть в консоли) — признак того, что в коде используется jQuery, это её фирменный знак.

jQuery настолько распространена, что на её основе уже делают другие библиотеки: всевозможные галереи, переключалки, интерфейсные штуки, формы и т. д. Чтобы такие библиотеки работали, сначала в браузере должна быть загружена сама jQuery, а уже потом — нужная вам библиотека.

Технически с точки зрения браузера $ — это просто объект в языке JavaScript. У него есть методы, которые должны быть прописаны, прежде чем браузер сможет их исполнить. И если на момент вызова этих методов они не были нигде прописаны, браузер справедливо возмутится. А они не будут прописаны только в одном случае: при загрузке jQuery что-то пошло не так.

Возможные причины незагрузки jQuery:

  • Её просто забыли добавить в код.
  • Она загружается с удалённого сайта, который сейчас для вас недоступен. Отключён интернет, сайт лежит, заблокирован или в его адресе опечатка.
  • При загрузке что-то пошло не так, и вместо jQuery прилетело что-то другое.
  • Уже после загрузки jQuery какой-то другой скрипт переопределил объект $ (и всё сломал).
  • Браузер запретил загрузку скрипта с другого сайта.
  • Она загружается после того, как её вызывают (а не до).
  • Загружается какая-то испорченная версия jQuery (маловероятно).

Понравилась статья? Поделить с друзьями:
  • Uncaught in promise typeerror fullscreen error
  • Uncaught in promise error recaptcha has already been rendered in this element
  • Uncaught in promise error could not establish connection receiving end does not exist
  • Uncaught in promise error cannot access a chrome url
  • Uncaught exception twig error loader with message