Jquery не определено ошибка как исправить

The "jQuery is not defined" error means a call for a specific jQuery that wasn't available when the website loaded. Here's how to fix it.

Whether you’re a stranger to WordPress errors or not, being met with “jQuery is not defined” while working on your website is never fun. It can be a startling and confusing message to see. Luckily, this is a standard error that sites using jQuery may experience at some point or another.

Perhaps your site is down, and when you check your browser console for errors, you see “jQuery is not defined.” Finding the error is the first step — so well done!

The next step is to resolve it. Because this is one of the more straightforward JavaScript errors to fix, it shouldn’t take you very long at all.

In this post, we’ll walk you through everything you need to know to fix it fast. That includes what the error means, why it may have happened in the first place — all critical information to prevent this error in the future. Finally, we’ll walk you through a few steps you can take to resolve it.

Let’s dive in!

Check Out Our Video Guide to Fixing the “jQuery Is Not Defined” Error

What Is the “jQuery Is Not Defined” Error?

The handy console log in your browser is where you’ll probably discover this error. But it’s not incredibly descriptive. What does “jQuery is not defined” actually mean?

In plain English, this error is trying to tell you that something on your site — may be a plugin — requires jQuery to function on your site. For some reason, when the browser tried to load the website and called for that specific jQuery, it was not available.

This error can potentially shut down your site to visitors. Because roughly 78% of the websites on the internet run on jQuery, this is a common error to find.

The Chrome dev tools console tab will read "jquery is not defined" in red

jQuery is not defined” error in the console log.

Whether you’re a stranger to WordPress errors or not, being met with “jQuery is not defined” while working on your website is never fun. 😫 Learn how to fix it here! ⬇️Click to Tweet

Potential Causes of the “jQuery Is Not Defined” Error

This error can be quite a surprise. Your site was working just fine yesterday — what happened? This might be a bit of a head-scratcher.

There are a few possible things that could have occurred that threw the “jQuery is not defined” error:

  1. Old plugins installed on your WordPress site are conflicting with ones that you installed and activated more recently. If you recently installed or activated new plugins or some of the plugins on your site have not been updated recently, this may be the cause.
  2. A slow or poor-performing hosting environment could increase the amount of time it takes your jQuery to perform when called. Double-check your server resources or error log to confirm this.
  3. The JavaScript on your website is running before the jQuery is fully loaded. Or perhaps a JavaScript file is not being correctly loaded when the page loads.
  4. The CDN that you’re using to improve your site performance was unable to reach your server. If you’re not using a CDN at all, you can rule out this possibility entirely.
  5. There’s an error or typo in your version of jQuery. Perhaps someone recently edited a core file or a plugin, which has now caused a conflict.

How To Fix the “jQuery Is Not Defined” Error

Before we dive into the fix, remember to make a backup of your website before editing code! Even the most seasoned developers make mistakes now and again, and having a backup on hand will prevent you from losing any important work as you troubleshoot.

If you have the option, resolve the error on a staging or development site first, as Kinsta customers do, then confirm the fix and push those changes live.

Once you’ve taken those necessary precautions, it’s time to fix that error.

Resolving this error takes some familiarity with adding, removing, and editing code. Don’t worry — you won’t need to write any code from scratch. But it would help if you were prepared to access your site’s code, either through SFTP or through your hosting environment.

It’s not ideal for editing code through the WordPress dashboard code editor. If you don’t already have a good text editor handy, now’s the time to install one.

Here are a few options you can utilize to resolve this error and get your site back up to visitors.

Method 1: Use the Network Tab to Debug if jQuery Is Loading

Look at the Network tab of your browser’s dev tools to see if jQuery is being loaded. This gives you one place to find a quick validation.

The alternative is looking through multiple plugins and themes that could be causing the error. Go through the code of your site and ensure that jQuery is included. It would be best if you only loaded it once.

If the jQuery library isn’t included, add it to your wp_enqueue_script() function with the following snippet:

wp_enqueue_script( 'tt-mobile-menu', get_template_directory_uri() .
'/js/mobile-menu.js', array('jQuery'), '1.0', true );

Locate this code by going to the wp-includes folder, then open the script-loader.php file. If this doesn’t work, or if you find that the jQuery library is, in fact, already included, move on to the following method.

Snippet can be pasted into any FTP editor, so long as it's in the script-loader.php file.

How your snippet will look in the script-loader.php file.

Method 2: Make Sure jQuery Is Loaded

You may experience the “jQuery is not defined error” when jQuery is included but not loaded. Make sure that it’s loaded by finding the script source and pasting the URL in a new browser or tab.

For example, if the <script src= is set to this:

Your snippet of text should look like this in your code editor.

The snippet of text you should look for to find the URL to test.

Then, copy and paste the http://code.jquery.com/jquery-1.11.2.min.js portion into a new window or tab. If the jQuery file loads and shows you the entire contents, you can check this off your list.

Method 3: Include Google-Hosted jQuery With a Local Fallback

This is a great option to include with your JavaScript because running jQuery on the localhost may improve your website experience overall. It will help avoid any other CDN jQuery loading issues.

// Fall back to a local copy of jQuery
window.jQuery || document.write(''))

With the note at the beginning, this is what your snippet of code should look like.

This is what your code snippet should look like in your code editor. Don’t forget the note!

Method 4: Add a Snippet to wp-config.php File

If none of the above work, open up the wp-config.php file and paste in the following snippet in its entirety:

/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
define('CONCATENATE_SCRIPTS', false);

Once added to the wp-config.php file, this is what your snippet will look like.

What the snippet will look like in your wp-config.php file.

Method 5: Insert the jQuery Library Manually

As a last method, you can go directly into the header.php file and add the jQuery library.

Here’s how:

  1. First, go to Google Hosted Libraries and copy the latest version of the jQuery library in its entirety.
  2. Open up your header.php file, found in your themes folder.
  3. Add in the jQuery library from step one. Make sure it goes in right after the head tag.
  4. Save the file when you’re done.

Make sure this is what the snippet looks like in your wp-config.php file

What the snippet will look like in your wp-config.php file.

Good news- you’ve found the “jQuery is not defined” error. 🙃 Now it’s time to solve it! ⬇️Click to Tweet

Summary

And there you have it! After following these steps, you should be able to resolve the “jQuery is not defined” error and access your site.

Since this problem is typically due to the browser’s inability to connect with your jQuery library, there are a limited number of solutions you can try. Most people find success with any of the above options.

If none of the above steps have resolved the error for some reason, it’s a good idea to contact your hosting company for support.

Have you encountered this error before? How did you solve it? Let us know in the comments section!


Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275 PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

Whether you’re a stranger to WordPress errors or not, being met with “jQuery is not defined” while working on your website is never fun. It can be a startling and confusing message to see. Luckily, this is a standard error that sites using jQuery may experience at some point or another.

Perhaps your site is down, and when you check your browser console for errors, you see “jQuery is not defined.” Finding the error is the first step — so well done!

The next step is to resolve it. Because this is one of the more straightforward JavaScript errors to fix, it shouldn’t take you very long at all.

In this post, we’ll walk you through everything you need to know to fix it fast. That includes what the error means, why it may have happened in the first place — all critical information to prevent this error in the future. Finally, we’ll walk you through a few steps you can take to resolve it.

Let’s dive in!

Check Out Our Video Guide to Fixing the “jQuery Is Not Defined” Error

What Is the “jQuery Is Not Defined” Error?

The handy console log in your browser is where you’ll probably discover this error. But it’s not incredibly descriptive. What does “jQuery is not defined” actually mean?

In plain English, this error is trying to tell you that something on your site — may be a plugin — requires jQuery to function on your site. For some reason, when the browser tried to load the website and called for that specific jQuery, it was not available.

This error can potentially shut down your site to visitors. Because roughly 78% of the websites on the internet run on jQuery, this is a common error to find.

The Chrome dev tools console tab will read "jquery is not defined" in red

jQuery is not defined” error in the console log.

Whether you’re a stranger to WordPress errors or not, being met with “jQuery is not defined” while working on your website is never fun. 😫 Learn how to fix it here! ⬇️Click to Tweet

Potential Causes of the “jQuery Is Not Defined” Error

This error can be quite a surprise. Your site was working just fine yesterday — what happened? This might be a bit of a head-scratcher.

There are a few possible things that could have occurred that threw the “jQuery is not defined” error:

  1. Old plugins installed on your WordPress site are conflicting with ones that you installed and activated more recently. If you recently installed or activated new plugins or some of the plugins on your site have not been updated recently, this may be the cause.
  2. A slow or poor-performing hosting environment could increase the amount of time it takes your jQuery to perform when called. Double-check your server resources or error log to confirm this.
  3. The JavaScript on your website is running before the jQuery is fully loaded. Or perhaps a JavaScript file is not being correctly loaded when the page loads.
  4. The CDN that you’re using to improve your site performance was unable to reach your server. If you’re not using a CDN at all, you can rule out this possibility entirely.
  5. There’s an error or typo in your version of jQuery. Perhaps someone recently edited a core file or a plugin, which has now caused a conflict.

How To Fix the “jQuery Is Not Defined” Error

Before we dive into the fix, remember to make a backup of your website before editing code! Even the most seasoned developers make mistakes now and again, and having a backup on hand will prevent you from losing any important work as you troubleshoot.

If you have the option, resolve the error on a staging or development site first, as Kinsta customers do, then confirm the fix and push those changes live.

Once you’ve taken those necessary precautions, it’s time to fix that error.

Resolving this error takes some familiarity with adding, removing, and editing code. Don’t worry — you won’t need to write any code from scratch. But it would help if you were prepared to access your site’s code, either through SFTP or through your hosting environment.

It’s not ideal for editing code through the WordPress dashboard code editor. If you don’t already have a good text editor handy, now’s the time to install one.

Here are a few options you can utilize to resolve this error and get your site back up to visitors.

Method 1: Use the Network Tab to Debug if jQuery Is Loading

Look at the Network tab of your browser’s dev tools to see if jQuery is being loaded. This gives you one place to find a quick validation.

The alternative is looking through multiple plugins and themes that could be causing the error. Go through the code of your site and ensure that jQuery is included. It would be best if you only loaded it once.

If the jQuery library isn’t included, add it to your wp_enqueue_script() function with the following snippet:

wp_enqueue_script( 'tt-mobile-menu', get_template_directory_uri() .
'/js/mobile-menu.js', array('jQuery'), '1.0', true );

Locate this code by going to the wp-includes folder, then open the script-loader.php file. If this doesn’t work, or if you find that the jQuery library is, in fact, already included, move on to the following method.

Snippet can be pasted into any FTP editor, so long as it's in the script-loader.php file.

How your snippet will look in the script-loader.php file.

Method 2: Make Sure jQuery Is Loaded

You may experience the “jQuery is not defined error” when jQuery is included but not loaded. Make sure that it’s loaded by finding the script source and pasting the URL in a new browser or tab.

For example, if the <script src= is set to this:

Your snippet of text should look like this in your code editor.

The snippet of text you should look for to find the URL to test.

Then, copy and paste the http://code.jquery.com/jquery-1.11.2.min.js portion into a new window or tab. If the jQuery file loads and shows you the entire contents, you can check this off your list.

Method 3: Include Google-Hosted jQuery With a Local Fallback

This is a great option to include with your JavaScript because running jQuery on the localhost may improve your website experience overall. It will help avoid any other CDN jQuery loading issues.

// Fall back to a local copy of jQuery
window.jQuery || document.write(''))

With the note at the beginning, this is what your snippet of code should look like.

This is what your code snippet should look like in your code editor. Don’t forget the note!

Method 4: Add a Snippet to wp-config.php File

If none of the above work, open up the wp-config.php file and paste in the following snippet in its entirety:

/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
define('CONCATENATE_SCRIPTS', false);

Once added to the wp-config.php file, this is what your snippet will look like.

What the snippet will look like in your wp-config.php file.

Method 5: Insert the jQuery Library Manually

As a last method, you can go directly into the header.php file and add the jQuery library.

Here’s how:

  1. First, go to Google Hosted Libraries and copy the latest version of the jQuery library in its entirety.
  2. Open up your header.php file, found in your themes folder.
  3. Add in the jQuery library from step one. Make sure it goes in right after the head tag.
  4. Save the file when you’re done.

Make sure this is what the snippet looks like in your wp-config.php file

What the snippet will look like in your wp-config.php file.

Good news- you’ve found the “jQuery is not defined” error. 🙃 Now it’s time to solve it! ⬇️Click to Tweet

Summary

And there you have it! After following these steps, you should be able to resolve the “jQuery is not defined” error and access your site.

Since this problem is typically due to the browser’s inability to connect with your jQuery library, there are a limited number of solutions you can try. Most people find success with any of the above options.

If none of the above steps have resolved the error for some reason, it’s a good idea to contact your hosting company for support.

Have you encountered this error before? How did you solve it? Let us know in the comments section!


Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275 PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

$ 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 (маловероятно).

Вы чувствуете себя в ловушке ошибок jquery WordPress? Вы хотите исправить ошибку «Uncaught ReferenceError: jQuery is not defined» на веб-сайте WordPress? Затем давайте посмотрим, как определить и, наконец, удалить эту ошибку.

JavaScript используется для чего угодно, от создания интерактивности на странице WordPress, например, для создания анимации и эффектов. Какие бы причудливые функции вы ни видели на странице WordPress, они исходят от JavaScript. Хотя это очень популярно для обеспечения гибкости, при этом очень часто возникают ошибки времени выполнения. Одна из наиболее распространенных ошибок JavaScript в WordPress – «jquery не определен». Это заставляет вещи останавливаться или не работать на вашем сайте WordPress. Здесь, в конструкторе веб- сайтов WordPress Templatetoaster, давайте подробно рассмотрим причины этой проблемы и процедуру ее устранения.

Распространенные причины появления сообщения «Uncaught ReferenceError: jQuery Is Not Defined» в WordPress

Есть несколько распространенных причин, по которым вы сталкиваетесь с ошибкой «jquery не определен» в WordPress. Это следующие:

  1. Один из ваших плагинов конфликтует с другими плагинами, особенно со старыми.
  2. JavaScript запускается до полной загрузки страницы по очереди до полной загрузки jQuery.
  3. Возможно, jQuery, размещенный на CDN, заблокирован или не работает.

Из-за этого у вас возникают проблемы, например, некоторые из ваших плагинов не работают, анимация слайдера не воспроизводится и многое другое. Итак, вам нужно хорошее решение, чтобы исправить эту проблему. Здесь на Templatetoaster сайте застройщика, давайте посмотрим, что вы можете сделать, чтобы избавиться от этой проблемы:

Решение ошибки «Uncaught ReferenceError: jQuery is not defined»

Как только вы познакомитесь с точками, вы сможете увидеть исходный код, нажав Ctrl + U. Откроется новое окно для отображения исходного кода. Здесь вы можете легко найти вхождения «jQuery». И вы можете исправить эту ошибку, следуя следующему подходу:

Шаг 1. Включение библиотеки jQuery

Когда вы просматриваете код, убедитесь, что jQuery включен и загрузится до вашего скрипта. Даже jQuery следует загружать только один раз. Если он загружается несколько раз, это вызовет проблемы.

Если он не включен, передайте его как третий аргумент в вашей функции wp_enqueue_script() следующим образом:

wp_enqueue_script( 'tt-mobile-menu', get_template_directory_uri(). '/js/mobile-menu.js', array('jquery'), '1.0', true );

Шаг 2: структура файла JavaScript

Во-вторых, вы убедитесь, что ваш JavaScript запускается следующим образом:

jQuery(document).ready(function()

{

jQuery(#selector) ...

});

Альтернативный вариант: включение кода в функцию

Если вы хотите использовать по умолчанию символ «$», вы можете заключить код в функцию следующим образом:

(function($) {

// Use $() inside of this function

$(#selector) ...

})(jQuery);

Шаг 3. Убедитесь, что jQuery загружен

Иногда возникают проблемы, потому что jQuery не загружен, хотя включен. Итак, чтобы убедиться, что jQuery загружен, скопируйте URL-адрес из сценария src и вставьте его в новую вкладку браузера. Например: Если сценарий src такой:

<script src="http://code.jquery.com/jquery-1.11.2.min.js" type="text/javascript"></script>

Вы скопируете только URL-адрес http://code.jquery.com/jquery-1.11.2.min.js и откроете его в новой вкладке браузера. Он покажет вам содержимое файла jquery, если он загружен правильно.

Если проблемы по-прежнему возникают, значит, в вашем коде есть ошибка. Итак, проверьте это внимательно.

Вывод

Итак, здесь, в конструкторе веб- сайтов Templatetoaster, обсуждается возможное решение для исправления ошибки jQuery is not defined. Это нельзя назвать оптимальным решением, так как определить точную причину проблемы непросто. Но в большинстве случаев это решение работает хорошо. Речь шла об удалении распространенной ошибки в WordPress – «jQuery не определен» после выявления ее причин. Эта простая процедура потребует всего лишь нескольких минутных изменений за короткий промежуток времени, и все готово !!

Надеюсь, это поможет вам !! Если у вас есть какие-либо вопросы, вы можете оставить сообщение в разделе комментариев ниже.

Источник записи: https://blog.templatetoaster.com

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

Для продвинутых разработчиков JavaScript (и продвинутых разработчиков jQuery) среди наших читателей эта статья не очень поможет. Вместо этого мы сосредоточимся на тех, кто только начинает работать с jQuery.

Возможно, вы прошли несколько учебных пособий по JavaScript, создали несколько небольших сайтов или проектов, которые в некоторой степени включают JavaScript в страницу (или сайт), и теперь вы готовы начать работу с новым фреймворком или библиотекой.

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

Как ни печально изучать что-то новое, преодолевать контрольно-пропускной пункт, а затем повторять его чуть дальше, серебряная полоса состоит в том, что есть вероятность, что ваши проблемы будут решены кем-то другим.

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

И это именно то, что мы собираемся осветить в этом уроке. В частности, мы будем говорить о проблеме, когда вы получите сообщение об ошибке:

Uncaught ReferenceError: jQuery is undefined

Понимание проблемы

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

Uncaught ReferenceError jQuery не определен

Если вы знакомы с JavaScript, то вы знаете, насколько undefined может быть undefined то есть речь идет о глобальном объекте или примитивном значении? Это выходит за рамки этого поста (не каламбур!), Но даже если вы не знакомы ни с одним из определений, это не значит, что вы не способны диагностировать проблему.

Настройте Песочницу

Во-первых, давайте продолжим и настроим страницу, которая включает в себя основы того, что нам нужно для работы с библиотекой jQuery, чтобы воспроизвести ошибку, которую мы видим выше.

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

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

<!doctype html>

<html class=”no-js” lang=””>

    <head>

        <meta charset=”utf-8″>

        <meta http-equiv=”X-UA-Compatible” content=”IE=edge,chrome=1″>

        <title></title>

        <meta name=”description” content=””>

        <meta name=”viewport” content=”width=device-width, initial-scale=1″>

        <link rel=”stylesheet” href=”css/normalize.min.css”>

        <link rel=”stylesheet” href=”css/main.css”>

        <script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js”></script>

    </head>

    <body>

        <p>This is a basic HTML sandbox.</p>

    </body>

</html>

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

Хотя CSS не является обязательным, JavaScript не является. Обратите внимание, что мы включаем библиотеку jQuery из сети доставки контента (или CDN), поэтому нам не нужно включать ее в исходные файлы нашего проекта.

Далее, давайте создадим исходный файл JavaScript, который мы сможем использовать для воссоздания вышеуказанной ошибки и написания некоторого тестового кода для решения проблемы. Мы назовем это main.js

После этого включите исходный файл в ваш HTML-документ так, чтобы конечный файл выглядел так:

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

<!doctype html>

<html class=”no-js” lang=””>

    <head>

        <meta charset=”utf-8″>

        <meta http-equiv=”X-UA-Compatible” content=”IE=edge,chrome=1″>

        <title></title>

        <meta name=”description” content=””>

        <meta name=”viewport” content=”width=device-width, initial-scale=1″>

        <link rel=”stylesheet” href=”css/normalize.min.css”>

        <link rel=”stylesheet” href=”css/main.css”>

        <script src=”js/main.js”></script>

        <script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js”></script>

    </head>

    <body>

        <p>This is a basic HTML sandbox.</p>

    </body>

</html>

Теперь у вас должна быть возможность загрузить страницу в браузере и увидеть что-то почти такое же, как изображение консоли, показанное выше.

Убедитесь, что ваш JavaScript загружен

Прежде чем идти дальше, давайте продолжим и убедимся, что файл JavaScript загружен правильно. Для этого мы настроим простое предупреждение, чтобы сообщение отображалось всякий раз, когда страница загружается в браузере.

JavaScript загружен

Чтобы увидеть этот экран, внесите следующие изменения в свой исходный файл JavaScript:

1

2

3

$(function() {

    alert( ‘JavaScript Loaded!’ );

});

Затем убедитесь, что вы переупорядочили файлы JavaScript из:

1

2

<script src=”js/main.js”></script>

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js”></script>

Для того, чтобы:

1

2

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js”></script>

<script src=”js/main.js”></script>

Мы поговорим об этом немного позже.

На этом этапе обновите страницу. Предполагая, что все прошло хорошо до этого момента, вы должны увидеть диалог, как показано на рисунке выше. Если это не сработает, просмотрите приведенный выше код (или загрузите файлы, прилагаемые к этому руководству) и убедитесь, что все загружено правильно.

Воспроизведение проблемы

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

1. jQuery загружается после вашего кода

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

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

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

После изменения полный HTML-код должен выглядеть следующим образом:

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

<!doctype html>

<html class=”no-js” lang=””>

    <head>

        <meta charset=”utf-8″>

        <meta http-equiv=”X-UA-Compatible” content=”IE=edge,chrome=1″>

        <title></title>

        <meta name=”description” content=””>

        <meta name=”viewport” content=”width=device-width, initial-scale=1″>

        <link rel=”stylesheet” href=”css/normalize.min.css”>

        <link rel=”stylesheet” href=”css/main.css”>

        <script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js”></script>

        <script src=”js/main.js”></script>

    </head>

    <body>

        <p>This is a basic HTML sandbox.</p>

    </body>

</html>

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

2. Конфликтующий плагин или файл

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

В частности, jQuery – это имя функции в исходном коде jQuery. Библиотека использует $ как синоним или ярлык, так как он, вероятно, будет использоваться так часто. Это делает код легче набирать и легче читать.

Нет конфликтов

Но это не единственный код JavaScript, который использует эту функцию, и иногда разработчикам нужно будет использовать другую функцию или передать $ другому кусочку исходного кода. Для этого они могут использовать jQuery.noConflict() .

Прямо из API :

Многие библиотеки JavaScript используют $ как имя функции или переменной, так же как и jQuery. В случае jQuery $ – это просто псевдоним для jQuery , поэтому все функции доступны без использования $ .

Если вам нужно использовать другую библиотеку JavaScript вместе с jQuery, верните управление $ back другой библиотеке с помощью вызова $.noConflict() . Старые ссылки на $ сохраняются во время инициализации jQuery; noConflict() просто восстанавливает их.

Так что где-то в коде, который вы включили, есть шанс, что другой разработчик сделал вызов этой функции. Таким образом, функция $ не будет доступна. Это может потенциально вызывать функцию, jQuery самого jQuery , или вызывать функцию, которая не undefined .

В нашем случае нас интересует последнее. Чтобы решить эту проблему, мы можем попробовать пару решений. Во-первых, мы можем попытаться восстановить доступ к функции $ , просто вызвав jQuery.noConflict() еще раз. Хотя это может решить проблему, это может также привести к другой проблеме, которая существует, если в ваш код включена другая платформа, библиотека или какой-либо другой модуль.

С этой целью я рекомендую использовать это только тогда, когда вы абсолютно уверены, что знаете, что делаете, и что это не повлияет на другие фреймворки.

Правильное определение объема $

Но что, если вы не знаете, что это не повлияет на другие фреймворки? Что тогда? В этом случае у вас есть возможность инициализировать ваш код так, чтобы он начинался с базовой функции jQuery а затем использовал $ для включения функции ярлыка в контекст вашего собственного кода.

Звучит сложно? Не беспокойся Это не плохо. Давайте изменим наш исходный файл JavaScript, чтобы он содержал следующее:

1

2

3

4

5

6

7

8

(function( $ ) {

    ‘use strict’;

    $(function() {

        alert( ‘JavaScript Loaded!’ );

    });

})( jQuery );

Хорошо, вот что происходит:

  1. Мы объявляем анонимную функцию, которая принимает один аргумент (в нашем случае, jQuery ).
  2. Функция будет передана и на нее будет ссылаться $ и она будет видна только в контексте нашей анонимной функции.

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

Не каждый делает это таким образом, но это очень распространенный, очень безопасный способ справиться с этим, чтобы вы могли избежать всего undefined сообщения об ошибке.

3. Есть ли еще?

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

Более того, изменение jQuery для выполнения того, что вы хотите, может привести к тому, что он сломает что-то другое (что, очевидно, никогда не бывает хорошим)

Вместо этого лучше придерживаться того, что, как мы знаем, безопасно, например, с помощью анонимного подхода, упомянутого выше, и не злоупотреблять такими вещами, как метод noConflict() . В конце концов, частью хорошей разработки является не только хорошая игра с кодом других людей, но и написание кода, с которым другие тоже могут играть хорошо.

Вывод

Как указано выше, существует множество разных вещей, которые могут вызвать сообщение jQuery is undefined в вашей консоли. Мы попытались рассмотреть несколько наиболее распространенных проблем в приведенных выше примерах.

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

В любом случае, это, надеюсь, поможет объяснить, в чем заключается проблема, и некоторые способы, которые помогут вам в ее диагностике. Если ваше решение не было изложено здесь, пожалуйста, оставьте его в комментариях.

Кроме того, если у вас есть другие вопросы, не стесняйтесь оставлять их в комментариях ниже, и я постараюсь ответить на них в меру своих возможностей.

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.

Понравилась статья? Поделить с друзьями:
  • Jquery как изменить содержимое span
  • Jquery как изменить значение атрибута
  • Jquery как изменить значение select
  • Jquery как изменить value input
  • Jquery как изменить src картинки