Jquery ошибка wordpress

Вы чувствуете себя в ловушке ошибок 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

I am using a test environment to try to get jquery working in wordpress, the installation version is 3.2.1 and the theme is 2010 (although I have tried this in a few different themes, same result). There are no plug-ins installed.

Basically I am putting this in the header file to see if I can get jQuery to work.

<script type="text/javascript">
jQuery(document).ready(function(){
alert('test');
    });
</script>

have also tried this

jQuery(document).ready(function($){

and this

$j=jQuery.noConflict(); 
// Use jQuery via $j(...)
$j(document).ready(function(){
  alert('test');
});

I can not seem to get it to display the alert when the page loads. When I check firebug the script has loaded.

jQuery works fine when not used in conjunction with WP and all scripts tested outside of WP perform as expected.

Should it work in WP 3.2.1? What can I try?

asked Aug 28, 2011 at 3:19

macmiller's user avatar

1

Have you added the actual jQuery script file?

There are a number of ways to do this, but I usually use the following method by including this code in the functions.php file.

<?php
    function add_jquery() {
       wp_enqueue_script( 'jquery' );
    }    

    add_action('init', 'add_jquery');
?>

Here is also a good resource for more jQuery + WordPress usage: http://www.ericmmartin.com/5-tips-for-using-jquery-with-wordpress/

answered Aug 28, 2011 at 3:54

Paul Sham's user avatar

Paul ShamPaul Sham

3,1852 gold badges24 silver badges31 bronze badges

1

Make sure WP itself (or another installed plugin) does not have an already embedded jQuery version that conflicts with yours.. View the source of your page and make sure only one jQuery version is loaded. Should go w/o problems.

answered Aug 28, 2011 at 3:43

Ruslan Abuzant's user avatar

By using wp_enqueue_script you are sure the jQuery library is loaded ONCE. You can see here how to load a JS file.

answered Aug 28, 2011 at 12:33

Ionuț Staicu's user avatar

Ionuț StaicuIonuț Staicu

21.4k11 gold badges51 silver badges58 bronze badges

Beside the way mentioned by Paul Sham which is absolutely correct, following way is also helpful which is also describe at THIS link.

function include_jQuery() {
    if (!is_admin()) {
        // comment out the next two lines to load the local copy of jQuery
        wp_deregister_script('jquery'); 
        wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js', false, '1.8.3'); 
        wp_enqueue_script('jquery');
    }
}
add_action('init', 'include_jQuery');

answered Jan 7, 2013 at 18:08

enam's user avatar

enamenam

1,1791 gold badge10 silver badges24 bronze badges

if( !is_admin()){
  wp_deregister_script('jquery');
  wp_register_script('jquery',       ("http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"), false, '1.3.1');
  wp_enqueue_script('jquery'); 
}

put this code in your current wordpress theame’s function.php file in between

Thirumalai murugan's user avatar

answered Aug 24, 2013 at 5:38

Nandkishor's user avatar

I find the other one, write this at the beginning of your script.
$ = jQuery.noConflict();

answered Jun 7, 2020 at 9:35

imnhasan's user avatar

imnhasanimnhasan

931 gold badge2 silver badges10 bronze badges

EDIT:

The answer below was not intended as step-by-step instructions about how to add jQuery to WordPress. I’m simply asking him to check and see if it’s already there, then I’m telling him to «not include it again» IF it’s already there.

As mentioned in comments, wp_enqueue_script is the absolute best way to add jQuery to WordPress, whenever you need to add jQuery.


Of course jQuery works within WordPress but I am not sure if it’s already included within the Twenty-Ten theme by default. Check to see if the script includes tags are there. You need something like this in the header someplace before you can call any JavaScript that uses jQuery…

<script type='text/javascript' src='/jquery.js?ver=1.6.1'></script>

(Make sure you’re not including it more than once or multiple versions.)

answered Aug 28, 2011 at 3:42

Sparky's user avatar

SparkySparky

98.2k25 gold badges199 silver badges285 bronze badges

8

You’re probably terrified every time the error ‘jQuery is not defined’ appears. This query can definitely shut down your entire website. If your page is one of 73% of the sites which run on jQuery, then this error may be a real struggle.

To make things clear, jQuery is a library designed to simplify HTML with all its components:

  • DOM
  • Event handling
  • Animation
  • Dynamic content

Although jQuery is a JavaScript library, it can often conflict with the other libraries JavaScript uses. This is the main reason for the appearance of the error in WordPress: “jQuery is not defined’. This means the system is unable to read your code, because the jQuery works as a middleman between the two parts.

Below, is how it looks on your screen, in case you haven’t experienced this problem yet:

WordPress Reference Error is not defined: Fix jQuery is not defined

Here is why you get the “Uncaught Reference Error: jQuery Is Not Defined” in WordPress

There are a variety of causes for this problem.The majority of users should find the following two reasons are very common. Carefully read and analyze which one could be the main cause of the error on your screen:

Old plugins don’t get along well with the new ones

Always take into account that for as many parties you have in the coding, you have as many chances for their variables to conflict.

This can also be the case of the jQuery code in contact with other plugins or snippets. Let’s take, for example, the symbol $, which jQuery uses as a shortcut for its own name. In the code of another third party, the $ can have another value. Both values can’t exist at the same time in the same program. That’s why “jQuery is undefined”.

However there are more ways to handle this problem, which you can easily find online.

Too much work for your CDN-hosted jQuery

Remember that the browser sends the uncaught reference error, jQuery is not defined, after only half a minute of loading. This means that your CDN-hosted jQuery has less than 30 seconds to perform the action. A slow or unreliable host would be the cause of the error in this case.

jQuery is not fully loaded before JavaScript runs

The first rule in working with dependency products such as jQuery is keeping the order of loading between it and the rest of the code. First, you should completely load the jQuery. Then your code will function properly using the data from the dependency. Otherwise, the error “jQuery $ is not defined” will surely appear.

The explanation is logical. When the JavaScript code loads before the jQuery code, the latter is not included in the program. Thus, it cannot be used, so the ‘not defined’ message can be understood literally.

I’m interrupting the article to tell you about BeTheme, the definitive multipurpose theme. If trying to satisfy multiple clients has become more stressful than rewarding, BeTheme is the solution for that.

BeTheme’s selection of hundreds of customizable, responsive pre-built websites is the highlight and a proven stress reducer.

The customizability of the theme makes it a dream come true for its users. There are 4 types of Page Builders that you can use with it: WPBakery, BeBuilder, and Elementor among them.

And now with the Live Builder, it’s even more impressive.

Check out BeTheme and see why our users love it!

The rest of the article is down below.

Is the framework properly implemented?

Another problem may be the fact that each framework works differently.

The order of the code snippets is of vital importance. This may be one of the causes of the error as well as other code conflicts between sources. Here is an example. Placing the JavaScript references at the bottom of the program, before you end the body tag, is not always helpful. The advantage is that this technique helps with decreasing loading time per page. Yet, you risk getting the ‘jQuery $ not defined’ error if references of jQuery appear before it’s loaded. There are frameworks that automatically manage this problem,but these lead to slower performance.

Blocked CDN-hosted jQuery

When using a library from Google, there are more chances for your jQuery hosted on CDN to get shut down. Filters or proxy services are the most likely causes of this inconvenience. However, such cases usually happen in China or Indonesia, due to the huge number of requests located in this geographical area.

This can bring many little problems inside your programs, such as animation lagging or plugin deactivation.

How to solve the ‘jQuery is not defined’ error?

Finding the root cause is the first step in eliminating this problem. However, in many cases, this is not as easy as it seems. It can be a plugin or a theme or something else and it may be difficult to find the right cause when it’s a combination. Incompatibility between plugin and themes is just an example and that’s a real struggle!

If you can’t find the initial problem, check some settings throughout the program. First of all, make sure your jQuery file is fully loaded into the host program. Remember to give all the necessary permissions to avoid security issues interfering with the running of the program.

However, loading your jQuery in the program is not enough. The important detail is that the plugin itself gets loaded before jQuery, which is how you can avoid the ‘$ not defined’ message.

The problem is usually caused by a mistake in the code. In order to fix it, use the keyboard Ctrl + U to access the source code. Then you can analyze and find any reference to jQuery. One of them should clearly have a problem.

Here are some approaches that we propose to help you with those coding problems:

Method 1

Add the following snippet in your wp-config.php file. Don’t cut out the define statements:

/** Absolute path to the WordPress directory. */

if ( !defined('ABSPATH') )

define('ABSPATH', dirname(__FILE__) . '/');

define('CONCATENATE_SCRIPTS', false);

Method 2

This is another way of approaching the problem. Through this coding segment, we show you how to include Google-hosted jQuery with a local/alternate fallback.

// First try loading jQuery from Google's CDN
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

// Fall back to a local copy of jQuery if the CDN fails
<script>
window.jQuery || document.write('<script src="http://mysite.com/jquery.min.js"><\/script>'))
</script>

This is an official solution provided by the jquery.com website. When jQuery is not defined because of some loading issues then using your own domain will likely help. You’ll have a cached version, which an advantage worth taking into account.

There’s also another option for you to solve things quicker. Download the application Rails, which will automatically manage the fallback process.

Actually, this technique will allow you to solve the problem easily and it’ll also bean advantage for your website. It will run on the localhost which will make the browsing experience even more pleasant for your visitors and avoid any other CDN jQuery loading failures.

Method 3

Uncaught ReferenceError: jQuery is not defined occurring on your WordPress website? Then you are at the right place, as I’m going to discuss in detail how you can fix jQuery errors in WordPress.”

Most of the website are using jQuery these days. In fact, this JavaScript library is used for anything from prompting interactivity into WordPress pages like hovers to creating animations and effects. Whatever fancy effects you see on any WordPress site, it is all javascript. Although it is known to offer high flexibility, it is also common to experience runtime errors.

One of the most common JavaScript errors in WordPress is “jQuery is not defined”. The error message means that the website cannot call a function from the jQuery JavaScript library. As a result, one, or several website elements may stop, or not work properly.

Here in this TemplateToaster WordPress Theme Builder, blog I’m going to discuss in detail ways to find and fix this common jQuery error in WordPress. So, let’s begin.

jQuery is not defined is a common WordPress error that occurs when a website calls for a jQuery function but the library is unable to load the function properly. In simple words, this error may occur on your website because for some reason, when the browser tried to load the website and called for that specific jQuery file, it was unavailable.

There are many reasons you may come across the “jQuery is not defined” error. Some of these are mentioned below.

What Causes “jQuery is Not Defined Error” on WordPress Site?

There are many reasons why you may come across the jQuery is not defined error while using a WordPress website. Here are some of the potential reasons why you may experience an “UnCaught ReferenceError” jQuery is not defined” error while using the WordPress site.

  • Conflicting plugins: The old plugins installed on your WordPress website are conflicting with the ones that you have recently installed. So if you have recently installed or updated plugins on your website or some of the plugins on your website have not been updated, then this may be the cause for the jQuery not defined error.
  • A slow or poor-performing hosting environment: This can increase the total time it takes for the jQuery to respond when requested. Make sure to check your server resources or the error log to validate this.
  • Overloading your CDN-hosted jQuery: If you are using CDN-hosted jQuery then it might be unable to reach out to the server. A slow or inconsistent host can be the cause of the error. Also, it could be down or may not be able to reach out to the server because of many requests. If you are not using CDN then eliminate this reason.
  • JavaScript on your website is running before the jQuery is fully loading. First, the jQuery should fully load, only then the code will work correctly, using the data from the jQuery dependency.
  • The framework may not be implemented correctly. The order of code snippets is very important. This can be the reason for the error, and also for other code issues between the sources.
  • There might be an error or typing issue in the version of jQuery. Maybe you’ve recently edited a file or plugin, which may be causing the issue.

It might be the reason why you may come across problems like some of the plugins not working properly, slider animations not playing, and more. So, it is important to know how to fix jQuery errors on WordPress.

How to Fix WordPress Error “Uncaught ReferenceError: jQuery is not defined”?

Now that you know the most common cause of jQuery is not defined error, it is time to understand the solutions that can help you fix this WordPress error. But before we dive into the solutions, make sure to make a backup of your website, you can use the WordPress plugin for backup. Having a backup will help you lose any important data.

Solutions to Fix “jQuery Is Not Defined Error”

Method 1: Inclusion of jQuery Library

The first thing you need to do is check the code and make sure the jQuery is included and will load before the script. Also, the jQuery should load once only. If it is loading multiple times it will cause the error.

Check out the Network tab of your browser’s dev tools to know if the jQuery is being loaded or not. This way you can quickly check and confirm.

Alternatively, you can also check various plugins and themes that may be causing the error. Make sure to review the code of your website and check if jQuery is included. It is best if you only load it once.

However, if jQuery is not included, then pass it as a third argument, and add it to your wp_enqueque_script() function as given below snippet

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

To find this code go to the wp-includes folder, and then open the script-loader.php file. However, if this method does not work, or you find out that the jQuery is already included then follow the next solutions.

Method 2: Make Sure the jQuery is Loaded

The jQuery is not defined error may also occur if jQuery is included but not fully loaded. So you need to make sure it is fully loaded. Simply find the script source and paste the URL into a new browser or tab.

For example, if the <script src- is set as:

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

Then you need to copy and paste the http://code.jquery-1.11.2.min.js section into the new window or tab. If the jQuery loads and shows the complete content, then you can proceed with the next solution.

Method 3: Structure of the JavaScript File

Also, make sure to check the structure of the JavaScript file is correct. It should start as:

jQuery(document).ready(function()
{
jQuery(#selector) ...
});

Alternate: Wrapping the code in a function
If you want to go with the default “$” symbol, you can wrap the code within a function as follows –

(function($) {
// Use $() inside of this function
$(#selector) ...
})(jQuery);

Method 4: Add Google-Hosted jQuery With A Local FallBack

This is a good solution to add to your JavaScript as sometimes running jQuery on localhost can help enhance the overall website experience. Also, it helps resolve any other CDN-related issues.

// Fall back to a local copy of jQuery
window.jQuery || document.write('<script src="http://code.jquery.com/jquery.min.js"><\/script>’
))

Method 5: Add A Snippet to the wp-config.php File

If the above-mentioned solutions to fix jQuery not defined errors do not work then you need to define the file path (ABSPATH) in the WordPress core file. You need to insert the given below snippet in the wp-config.php file using a File Manager or FTP client.

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

Method 6: Add jQuery Library Manually

Well, if none of the solutions for how to fix jQuery errors in WordPress work, then this is the last method to fix the issue. You can directly go to the header.php file and insert the jQuery library. Here is how you can do it:

  • First of all, go to the Google-hosted libraries and copy the latest version of the CDN code snippet of the jQuery library.
  • Then, find the header.php file in the theme folder.
  • Open the header file and paste the jQuery library from step one right after the head tag as shown below:
    <head>
    
    <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
  • Lastly, make sure to save the changes.

How to Avoid “jQuery Not Defined” Error on WordPress?

Notably, there are two methods to insert the jQuery library into your WordPress website. The first one is to include the source code in the HTML files or a new JavaScript file.

You can do the first method easily- simply download the jQuery files or copy the jQuery CDN code snippet and insert the file path or URL in the header of the HTML files. We have already discussed how to do this in the above methods.

Although this is the easiest method, it requires you to update all of the HTML files using the latest jQuery version. This is the main reason why developers prefer the other method.

So, by adding the source code in a different JavaScript file, you only need to modify that particular file. And have it take effect on all of the HTML files that call the function.

Conclusion: Fix jQuery Is Not Defined Error

And that’s about it. After following the above-mentioned methods you should be able to fix the WordPress Error “Uncaught ReferenceError: jQuery is not Defined”.

The main reason for this error is that the browser is unable to connect with the jQuery library. So there are limited solutions to fix this issue. However, by following the methods mentioned in this post you should be able to resolve jQuery errors on your WordPress site.

However, if none of these solutions works make sure to contact your hosting provider for help. Hope you have got the necessary information, and this will help you out. If you have any queries you can post in the comment section below.

I know that jQuery is loaded, because I can switch out the $ for ‘jQuery’ and everything behaves as expected, but this will be a messy script if I can’t fix this

This script:

jQuery(document).ready(function(){
    $("ul.vimeo_desc_feed li a").click(function(){
        alert($(this).attr('href'));
        return false;
    })
});

Produces the error $ is not a function

This script:

jQuery(document).ready(function(){
    jQuery("ul.vimeo_desc_feed li a").click(function(){
        alert(jQuery(this).attr('href'));
        return false;
    })
});

works fine.

Volker E.'s user avatar

asked Oct 14, 2010 at 15:27

Mild Fuzz's user avatar

0

You can wrap your javascript inside a self-invoking function, then pass jQuery as an argument to it, using $ as the local variable name. For example:

(function($) {
  $(document).ready(function(){
    $("ul.vimeo_desc_feed li a").click(function(){
      alert($(this).attr('href'));
      return false;
    })
 });
}(jQuery));

should work as intended.

If I remember correctly the WP-supplied version of jQuery (the one you get if you wp_enqueue_script('jquery')) puts jQuery in no-conflict immediately, causing $ to be undefined.

answered Oct 14, 2010 at 15:38

nobody's user avatar

nobodynobody

2,4562 gold badges27 silver badges32 bronze badges

3

You’re almost there!

jQuery(document).ready(function($){
    $("ul.vimeo_desc_feed li a").click(function(){
        alert($(this).attr('href'));
        return false;
    })

});

You have to pass a reference to jQuery as the $ function into your method or it won’t work. If you just place a $ inside the first function() call as I did above, things will be working just fine.

answered Oct 14, 2010 at 15:41

EAMann's user avatar

EAMannEAMann

31.9k9 gold badges87 silver badges146 bronze badges

4

Passing a function to jQuery is shorthand for $(document).ready(...) then by placing $ as the first parameter of your callback, you create an alias for jQuery within that callback:

jQuery(function($) {
    $("ul.vimeo_desc_feed li a").click(function(){
        alert($(this).attr('href'));
        return false;
    });
});

You can see the documentation for this here.

user9447's user avatar

user9447

1,7527 gold badges29 silver badges54 bronze badges

answered Oct 9, 2013 at 23:18

rohmann's user avatar

rohmannrohmann

1711 silver badge3 bronze badges

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Joomla админка ошибка 403
  • Jquery post ошибка 500
  • Jungheinrich ese 120 коды ошибок
  • Joxi неопознанная ошибка
  • Jquery html ошибка

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии