Ошибка uncaught referenceerror jquery is not defined

I have a simple jquery click event

<script type="text/javascript">
    $(function() {
        $('#post').click(function() {
            alert("test"); 
        });
    });
</script>

and a jquery reference defined in the site.master

<script src="<%=ResolveUrl("~/Scripts/jquery-1.3.2.js")%>" type="text/javascript"></script>

I have checked that the script is being resolved correctly, I’m able to see the markup and view the script directly in firebug, so I must be being found. However, I am still getting:

$ is not defined

and none of the jquery works. I’ve also tried the various variations of this like $(document).ready and jQuery etc.

It’s an MVC 2 app on .net 3.5, I’m sure I’m being really dense, everywhere on google says to check the file is referenced correctly, which I have checked and checked again, please advise! :/

Selim Yildiz's user avatar

Selim Yildiz

5,2146 gold badges17 silver badges27 bronze badges

asked Feb 3, 2010 at 19:57

Paul Creasey's user avatar

Paul CreaseyPaul Creasey

28.3k10 gold badges54 silver badges90 bronze badges

11

That error can only be caused by one of three things:

  1. Your JavaScript file is not being properly loaded into your page
  2. You have a botched version of jQuery. This could happen because someone edited the core file, or a plugin may have overwritten the $ variable.
  3. You have JavaScript running before the page is fully loaded, and as such, before jQuery is fully loaded.

First of all, ensure, what script is call properly, it should looks like

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

and shouldn’t have attributes async or defer.

Then you should check the Firebug net panel to see if the file is actually being loaded properly. If not, it will be highlighted red and will say «404» beside it. If the file is loading properly, that means that the issue is number 2.

Make sure all jQuery javascript code is being run inside a code block such as:

$(document).ready(function () {
  //your code here
});

This will ensure that your code is being loaded after jQuery has been initialized.

One final thing to check is to make sure that you are not loading any plugins before you load jQuery. Plugins extend the «$» object, so if you load a plugin before loading jQuery core, then you’ll get the error you described.

Note: If you’re loading code which does not require jQuery to run it does not need to be placed inside the jQuery ready handler. That code may be separated using document.readyState.

Denis Tsoi's user avatar

Denis Tsoi

9,2308 gold badges37 silver badges53 bronze badges

answered Feb 3, 2010 at 20:27

Mike Trpcic's user avatar

Mike TrpcicMike Trpcic

25.3k8 gold badges78 silver badges114 bronze badges

10

It could be that you have your script tag called before the jquery script is called.

<script type="text/javascript" src="js/script.js"></script>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

This results as $ is not defined

Put the jquery.js before your script tag and it will work ;) like so:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

<script type="text/javascript" src="js/script.js"></script>

Elmo's user avatar

Elmo

6,37916 gold badges71 silver badges140 bronze badges

answered Dec 19, 2011 at 0:31

Hanky Panky's user avatar

5

First you need to make sure that jQuery script is loaded. This could be from a CDN or local on your website. If you don’t load this first before trying to use jQuery it will tell you that jQuery is not defined.

<script src="jquery.min.js"></script>

This could be in the HEAD or in the footer of the page, just make sure you load it before you try to call any other jQuery stuff.

Then you need to use one of the two solutions below

(function($){
// your standard jquery code goes here with $ prefix
// best used inside a page with inline code, 
// or outside the document ready, enter code here
 })(jQuery); 

or

jQuery(document).ready(function($){
// standard on load code goes here with $ prefix
// note: the $ is setup inside the anonymous function of the ready command
});

please be aware that many times $(document).ready(function(){//code here}); will not work.

answered Jan 27, 2014 at 10:37

Andrew Killen's user avatar

6

If the jQuery plugin call is next to the </body>, and your script is loaded before that, you should make your code run after window.onload event, like this:

window.onload = function() {
  //YOUR JQUERY CODE
}

`

so, your code will run only after the window load, when all assets have been loaded. In that point, the jQuery ($) will be defined.

If you use that:

$(document).ready(function () {
  //YOUR JQUERY CODE
});

`

the $ isn’t yet defined at this time, because it is called before the jQuery is loaded, and your script will fail on that first line on console.

Bruno Peres's user avatar

Bruno Peres

2,9711 gold badge21 silver badges19 bronze badges

answered Jun 25, 2014 at 21:21

dandapereira's user avatar

2

I just did the same thing and found i had a whole lot of

type="text/javacsript"

So they were loading, but no further hint as to why it wasn’t working. Needless to say, proper spelling fixed it.

Martijn Pieters's user avatar

answered Aug 9, 2011 at 2:35

George R's user avatar

George RGeorge R

3,7443 gold badges34 silver badges38 bronze badges

1

Use a scripts section in the view and master layout.

Put all your scripts defined in your view inside a Scripts section of the view. This way you can have the master layout load this after all other scripts have been loaded. This is the default setup when starting a new MVC5 web project. Not sure about earlier versions.

Views/Foo/MyView.cshtml:

// The rest of your view code above here.

@section Scripts 
{ 
    // Either render the bundle defined with same name in BundleConfig.cs...
    @Scripts.Render("~/bundles/myCustomBundle")

    // ...or hard code the HTML.
    <script src="URL-TO-CUSTOM-JS-FILE"></script>

    <script type="text/javascript">
      $(document).ready(function () {

        // Do your custom javascript for this view here. Will be run after 
        // loading all the other scripts.            
      });
    </script>
}

Views/Shared/_Layout.cshtml

<html>
<body>
    <!-- ... Rest of your layout file here ... -->

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

Note how the scripts section is rendered last in the master layout file.

answered Dec 3, 2013 at 14:58

angularsen's user avatar

angularsenangularsen

8,0401 gold badge67 silver badges83 bronze badges

2

It means that your jQuery library has not been loaded yet.

You can move your code after pulling jQuery library.

or you can use something like this

window.onload = function(){
  // Your code here
  // $(".some-class").html("some html");
};  

answered Jul 26, 2016 at 4:47

Nesar's user avatar

NesarNesar

5,5892 gold badges22 silver badges21 bronze badges

2

As stated above, it happens due to the conflict of $ variable.

I resolved this issue by reserving a secondary variable for jQuery with no conflict.

var $j = jQuery.noConflict();

and then use it anywhere

$j( "div" ).hide();

more details can be found here

answered Apr 17, 2015 at 10:57

Naveed Abbas's user avatar

Naveed AbbasNaveed Abbas

1,1571 gold badge14 silver badges37 bronze badges

make sure you really load jquery
this is not jquery — it’s the ui!

  <script language="JavaScript" 
    src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js">
  </script>

This is a correct script source for jquery:

 <script language="JavaScript"  src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

vhs's user avatar

vhs

9,1233 gold badges66 silver badges70 bronze badges

answered Jul 12, 2015 at 13:15

Wolfgang Fahl's user avatar

Wolfgang FahlWolfgang Fahl

14.9k11 gold badges90 silver badges184 bronze badges

after some tests i found a fast solution ,
you can add in top of your index page:

<script>
$=jQuery;
</script>

it work very fine :)

answered Sep 27, 2013 at 8:35

Mimouni's user avatar

MimouniMimouni

3,5443 gold badges28 silver badges36 bronze badges

3

I had the same problem and resolved it by using

document.addEventListener('DOMContentLoaded', () => {
 // code here
});

answered Jan 25, 2021 at 10:56

Walmac's user avatar

WalmacWalmac

1832 silver badges6 bronze badges

I got the same error message when I misspelled the jQuery reference and instead of type="text/javascript" I typed «…javascirpt». ;)

Brian Mains's user avatar

Brian Mains

50.5k35 gold badges145 silver badges256 bronze badges

answered Aug 3, 2010 at 14:28

alan's user avatar

2

It sounds like jQuery isn’t loading properly. Which source/version are you using?

Alternatively, it could a be namespace collision, so try using jQuery explicitly instead of using $. If that works, you may like to use noConflict to ensure the other code that’s using $ doesn’t break.

the Tin Man's user avatar

the Tin Man

158k42 gold badges214 silver badges303 bronze badges

answered Sep 12, 2012 at 8:07

Alexender Dumma's user avatar

That error means that jQuery has not yet loaded on the page. Using $(document).ready(...) or any variant thereof will do no good, as $ is the jQuery function.

Using window.onload should work here. Note that only one function can be assigned to window.onload. To avoid losing the original onload logic, you can decorate the original function like so:

originalOnload = window.onload;
window.onload = function() {
  if (originalOnload) {
    originalOnload();
  }
  // YOUR JQUERY
};

This will execute the function that was originally assigned to window.onload, and then will execute // YOUR JQUERY.

See https://en.wikipedia.org/wiki/Decorator_pattern for more detail about the decorator pattern.

answered Aug 28, 2016 at 7:25

Kyle McVay's user avatar

Kyle McVayKyle McVay

4783 silver badges13 bronze badges

I use Url.Content and never have a problem.

<script src="<%= Url.Content ("~/Scripts/jquery-1.4.1.min.js") %>" type="text/javascript"></script>

Peter Lillevold's user avatar

answered Feb 3, 2010 at 20:03

mdm20's user avatar

mdm20mdm20

4,4552 gold badges22 silver badges24 bronze badges

In the solution it is mentioned —
«One final thing to check is to make sure that you are not loading any plugins before you load jQuery. Plugins extend the «$» object, so if you load a plugin before loading jQuery core, then you’ll get the error you described.»

For avoiding this —

Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery’s case, $ is just an alias for jQuery, so all functionality is available without using $. If we need to use another JavaScript library alongside jQuery, we can return control of $ back to the other library with a call to $.noConflict():

answered Mar 22, 2012 at 4:54

I had this problem once for no apparent reason. It was happenning locally whilst I was running through the aspnet development server. It had been working and I reverted everything to a state where it had previously been working and still it didn’t work. I looked in the chrome debugger and the jquery-1.7.1.min.js had loaded without any problems. It was all very confusing. I still don’t know what the problem was but closing the browser, closing the development server and then trying again sorted it out.

answered Jan 20, 2012 at 15:32

cedd's user avatar

ceddcedd

1,7211 gold badge21 silver badges34 bronze badges

Just place jquery url on the top of your jquery code

like this—

<script src="<%=ResolveUrl("~/Scripts/jquery-1.3.2.js")%>" type="text/javascript"></script>

<script type="text/javascript">
    $(function() {
        $('#post').click(function() {
            alert("test"); 
        });
    });
</script>

answered Jun 3, 2012 at 13:06

vikrantx's user avatar

vikrantxvikrantx

5935 silver badges22 bronze badges

I had the same problem and it was because my reference to the jQuery.js was not in the tag. Once I switched that, everything started working.

Anthony

answered Oct 23, 2012 at 17:40

Anthony's user avatar

  1. Check the exact path of your jquery file is included.

    <script src="assets/plugins/jquery/jquery.min.js"></script>

if you add this on bottom of your page , please all call JS function below this declaration.

  1. Check using this code test ,

    <script type="text/javascript">
    /***
     * Created by dadenew
     * Submit email subscription using ajax
     * Send email address
     * Send controller
     * Recive response
     */
    $(document).ready(function() { //you can replace $ with Jquery
    
      alert( 'jquery working~!' );
    });
    

Peace!

answered Dec 17, 2014 at 8:41

Nickromancer's user avatar

NickromancerNickromancer

7,5418 gold badges58 silver badges76 bronze badges

This is the common issue to resolve this you have to check some point

  1. Include Main Jquery Library
  2. Check Cross-Browser Issue
  3. Add Library on TOP of the jquery code
  4. Check CDNs might be blocked.

Full details are given in this blog click here

answered Apr 9, 2020 at 17:32

Anju Batta's user avatar

0

I came across same issue, and it resolved by below steps.
The sequence of the scripts should be as per mentioned below

    <script src="~/Scripts/jquery-3.3.1.min.js"></script>
    <script src="~/Scripts/jquery-ui.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>

This sequence was not correct for my code, I corrected this as per the above and it resolved my issue of Jquery not defined.

answered Mar 11, 2021 at 15:09

AdityaUbale's user avatar

We have the same problem….but accidentally i checked folder properties and set something…

You have to check the properties of each folders that you’re accessing..

  1. right click folder
  2. ‘permissions’ tab
  3. set the folder access :
    OWNER: create and delete files
    GROUP: access files
    OTHERS: access files

I hope that this is the solution……

McGarnagle's user avatar

McGarnagle

101k31 gold badges228 silver badges260 bronze badges

answered Mar 14, 2012 at 8:53

RoyS_philippines's user avatar

When using jQuery in asp.net, if you are using a master page and you are loading the jquery source file there, make sure you have the header contentplaceholder after all the jquery script references.

I had a problem where any pages that used that master page would return ‘$ is not defined’ simply because the incorrect order was making the client side code run before the jquery object was created. So make sure you have:

<head runat="server">
    <script type="text/javascript" src="Scripts/jquery-VERSION#.js"></script>
    <asp:ContentPlaceHolder id="Header" runat="server"></asp:ContentPlaceHolder>
</head>

That way the code will run in order and you will be able to run jQuery code on the child pages.

answered Jan 18, 2013 at 16:03

Francis Musignac's user avatar

In my case I was pointing to Google hosted JQuery. It was included properly, but I was on an HTTPS page and calling it via HTTP. Once I fixed the problem (or allowed insecure content), it fired right up.

answered Feb 27, 2013 at 5:13

Anthony's user avatar

AnthonyAnthony

5,23511 gold badges49 silver badges86 bronze badges

After tried everything here with no result, I solved the problem simply by moving the script src tag from body to head

answered Aug 8, 2013 at 12:16

Spring's user avatar

SpringSpring

11.3k29 gold badges115 silver badges185 bronze badges

1

I was having this same problem and couldn’t figure out what was causing it. I recently converted my HTML files from Japanese to UTF-8, but I didn’t do anything with the script files. Somehow jquery-1.10.2.min.js became corrupted in this process (I still have no idea how). Replacing jquery-1.10.2.min.js with the original fixed it.

answered Feb 17, 2014 at 23:11

Gavin's user avatar

GavinGavin

7,4644 gold badges52 silver badges71 bronze badges

it appears that if you locate your jquery.js files under the same folder or in some subfolders where your html file is, the Firebug problem is solved. eg if your html is under C:/folder1/, then your js files should be somewhere under C:/folder1/ (or C:/folder1/folder2 etc) as well and addressed accordingly in the html doc. hope this helps.

answered May 4, 2014 at 14:18

sc123's user avatar

I have the same issue and no case resolve me the problem. The only thing that works for me, it’s put on the of the Site.master file, the next:

<script src="<%= ResolveUrl("~/Scripts/jquery-1.7.1.min.js") %>" type="text/javascript"></script>
<script src="<%= ResolveUrl("~/Scripts/bootstrap/js/bootstrap.min.js") %>" type="text/javascript"></script>

With src=»<%= ResolveUrl(«»)… the load of jQuery in the Content Pages is correct.

answered Oct 30, 2014 at 11:20

amelian's user avatar

amelianamelian

4261 gold badge6 silver badges16 bronze badges

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

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.

При программировании в 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 — что это такое?

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. Возможно, в расположении файла где-то есть опечатка либо сам файл был перемещен/удален из своей оригинальной директории. Если же используете онлайн-версию библиотеки, убедитесь, что с вашим сетевым подключением все в порядке.

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

Понравилась статья? Поделить с друзьями:
  • Ошибка unb на стиральной машине haier что это такое
  • Ошибка undefined is not an object evaluating
  • Ошибка unb на стиральной машине haier как исправить ошибку
  • Ошибка undefined error код ошибки 0
  • Ошибка unauthorized код ошибки 401