Uncaught typeerror undefined is not a function

В большинстве случаев ошибка Uncaught TypeError: $ is not a function связана с библиотекой jQuery. Вариантов несколько: либо библиотека просто не подключена, либо переменная $ используется другой библиотекой.

В первом случае проверьте подгружается ли библиотека до вызова. Проверьте нет ли библиотек, которые отдают ошибку 404. В консоли библиотек должна возвращать статус 304 или 200.

Скачать последнюю версию jQuey можно на официальном сайте или на нашем сайте в конце статьи.

Во втором случае проблема посложнее. Многие библиотеки JavaScript используют $как функция или имя переменной, так же как это делает Jquery. В случае Jquery, в $ это просто псевдоним jQuery, так что все функции доступны без использования $. Если вам нужно использовать другую библиотеку JavaScript наряду с JQuery, вернуть управление $ обратно в другую библиотеку с вызовом $.noConflict(). Так же можно использовать jQury вместо $.

I’m building a normal webpage which requires me to load about five CSS files and ten Javascript files.

    When loading them separately in the HTML page, my webpage loads fine.

Now for production, I concatenated all the Javascript into a single file, in the order needed, and all the CSS into another file. But when I try to run the web page with the concatenated files it throws an error saying:

Uncaught TypeError: undefined is not a function

On the line where jquery.min.js is being loaded in the concatenated Javascript file.

What can I do to mitigate this? I want to concatenate all files and minify them for production. Please help.

EDIT: I merged the Javascript and CSS in the order they were when they were being loaded individually and were working fine.

Читайте также:  Pbl60 la 7322p rev 1a характеристики

13 Answers 13

Assuming this problem still has not be resolved, a lot of individual files don’t end their code with a semicolon. Most jQuery scripts end with (jQuery) and you need to have (jQuery); .

As separate files the script will load just fine but as one individual file you need the semicolons.

You might have to re-check the order in which you are merging the files, it should be something like:

  1. jquery.min.js
  2. jquery-ui.js
  3. any third party plugins you loading
  4. your custom JS

This solution worked for me

Move your code inside the closure and use $ instead of jQuery

after seraching too much

I got the same error from having two references to different versions of jQuery.

In my master page:

And also on the page:

I had this problem recently with the jQuery Validation plug-in, using Squishit, also getting the js error:

I fixed it by changing the reference to the unminified jquery.validate.js file, rather than jquery.validate.min.js.

I think that the minified version of certain files, when further compressed using Squishit, for example, might in some cases not deal with missing semi-colons and the like, as @Dustin suggests, so you might have to experiment with which files you can doubly compress, and which you just leave to Squishit or whatever you’re bundling with.

For those out there who still couldn’t fix this, I did so by changing my ‘this’ to ‘$(this)’ when using jQuery.

I’ve run into the very same issue, when mistakenly named variable with the very same name, as function.

failed, generating OP’s mentioned error message.

Читайте также:  8Gadgetpack что это за программа

Fix to this was as simple as changing above line to:

I don’t know, how much does it helps in this situation, but I decided to put this answer for others looking for a solution for similar problems.

Yes, i also I fixed it changing in the js libraries to the unminified.

For example, in the tag, change:

Quiting the ‘min’ as unminified.

Thanks for the idea.

Remember: Javascript functions are CASE SENSITIVE.

I had a case where I’m pretty sure that my code would run smoothly. But still, got an error and I checked the Javascript console of Google Chrome to check what it is.

My error line is

And got the same error message:

Nothing seems wrong with the code above but it was not running. I troubleshoot for almost an hour and then compared it with my other running code. My error is that it was set to SetAttribute , which should be setAttribute .

In case there are any morons out there like me, I had this frustrating problem because I forgot a simple

keyword before instantiating a new object.

I just had the same message with the following code (in IcedCoffeeScript):

This seemed to me like regular ICS code. I unfolded the await-defer construct to regular CoffeeScript:

What really happend was that I tried to pass 1 callback function( with 2 parameters ) to function f expecting two parameters, effectively not setting cb inside f , which the compiler correctly reported as undefined is not a function .

The mistake happened because I blindly pasted callback-style boilerplate code. f doesn’t need an err parameter passed into it, thus should simply be:

In the general case, I’d recommend to double-check function signatures and invocations for matching arities. The call-stack in the error message should be able to provide helpful hints.

Читайте также:  World of tanks не открывается панель задач

In your special case, I recommend looking for function definitions appearing twice in the merged file, with different signatures, or assignments to global variables holding functions.

Последнее изменение: 23.02.2018 · 3548

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

Самая часта ошибка, которая возникает после обновления jQuery библиотек это ошибка: Uncaught TypeError: undefined is not a function

Данная ошибка чаще всего возникает из-за обновленных переменных и синтаксиса написания параметров, а именно у вас в скриптах прописано скорее всего так:

а должно быть так:

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

Rate this post

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *