Document ready error

I'm developing JS that is used in a web framework, and is frequently mixed in with other developers' (often error-prone) jQuery code. Unfortunately errors in their jQuery(document).ready blocks pre...

I’m developing JS that is used in a web framework, and is frequently mixed in with other developers’ (often error-prone) jQuery code. Unfortunately errors in their jQuery(document).ready blocks prevent mine from executing. Take the following simple sample:

<script type="text/javascript">
    jQuery(document).ready(function() {
        nosuchobject.fakemethod();       //intentionally cause major error
    });
</script>
<script type="text/javascript">
    jQuery(document).ready(function() {
        alert("Hello!");                 //never executed
    });
</script>

Shouldn’t the second ready block execute regardless of what happened in the previous? Is there a «safe» way to run jQuery(document).ready that will run even in the case of previous errors?

EDIT: I have no control/visibility over the error-prone blocks as they’re written by other authors and mixed in arbitrarily.

asked Dec 11, 2009 at 20:02

3hough's user avatar

3hough3hough

4051 gold badge6 silver badges14 bronze badges

3

I haven’t tried this code, but it should work (at least, the idea should anyway). Make sure you include it AFTER jquery, but BEFORE any potentially buggy scripts. (Not necessary, see comments.)

var oldReady = jQuery.ready;
jQuery.ready = function(){
  try{
    return oldReady.apply(this, arguments);
  }catch(e){
    // handle e ....
  }
};

answered Dec 11, 2009 at 20:11

Jerod Venema's user avatar

Jerod VenemaJerod Venema

43.7k5 gold badges66 silver badges109 bronze badges

3

To answer your question, both of the ready blocks are essentially combined into one given the way jQuery works:

<script type="text/javascript">
  jQuery(document).ready(function() {
      nosuchobject.fakemethod();       //intentionally cause major error
      alert("Hello!");                 //never executed
  });
</script>

So that’s why its not alerting per the error above. I don’t believe there is a way to fix this to make every ready function run regardless of former failures.

answered Dec 11, 2009 at 20:25

Mark Ursino's user avatar

Mark UrsinoMark Ursino

31k11 gold badges50 silver badges83 bronze badges

Have you attempted wrapping the error-prone commands in try…catch brackets?

$(function(){
    try {
        noObject.noMethod();
    } catch (error) {
        // handle error
    }
});

$(function(){
    try {
        alert("Hello World");
    } catch (error) {
        // handle error
    }
});

To avoid potential confusion, $(function(){ ... }); is functionally the same as $(document).ready(function(){ ... });

answered Dec 11, 2009 at 20:07

Sampson's user avatar

SampsonSampson

263k74 gold badges535 silver badges560 bronze badges

2

Here is solution, it will wrap any function sent to ready with try-catch block:

(function($){
    $.fn.oldReady = $.fn.ready;
    $.fn.ready = function(fn){
        return $.fn.oldReady( function(){ try{ if(fn) fn.apply($,arguments); } catch(e){}} );
    }
})(jQuery);

answered Dec 6, 2012 at 9:17

Aly's user avatar

You could re-reference jQuery before each of your code blocks. Your code would then use the fresh instance of the library, and it would execute. I’ve tested this in Safari 4.0.3 on OSX.

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
    <script type="text/javascript">
        jQuery(document).ready(function() {
            nosuchobject.fakemethod();       //intentionally cause major error
        });
    </script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>    
    <script type="text/javascript">
        jQuery(document).ready(function() {
            alert("Hello!");                 //executed!
        });
    </script>   

</head>
<body>

<p>hello world</p>

</body>
</html>

answered Dec 11, 2009 at 20:13

simeonwillbanks's user avatar

3

Добрый день читатели! Сегодня речь пойдет об очень-очень популярной ошибке, которая может возникать в CMS Joomla.

Представьте ситуацию. У вас сайта на Joomla, вы хотите, допустим, вставить сторонний скрипт, например, форму обратной связи на ajax. Вы точно знаете, что эта форма рабочая, не один раз ее использовали и тестировали. Вставляете на ваш сайт на joomla. Проверяете нажимая “отправить” и бамц – ничего не происходит.

В такой ситуации, первым делом вы будете проверять, подключен ли jquery вообще и правильная ли версия. Если вы уверенны, что все сделали правильно, но форма все равно не работает, необходимо проверить firebug консоль, чтобы понять, какую ошибку она вызывает.

В нашем случае ошибка будет

$(document).ready is not a function

По умолчанию в joomla используются некоторые js-фреймворки. Один из таких фреймворков – motools, который переписывает символ $, который вы пытаетесь использовать в ваших скриптах.

Решение проблемы

В вашем скрипте необходимо заменить все “$” на “jQuery”.

Например, если у вас написано

var posName = $("#posName").val();

То вы должны заменить на

var posName = jQuery("#posName").val();

Или у вас

$(document).ready(function()

А должно быть

jQuery(document).ready(function()

И т.д.

Вот и все 🙂 Решение проблемы не очень сложное. Если возникли вопросы, пишите в комментариях

[Solved] $(document).ready is not a function

July 12, 2012
Programming

Solve $(document).ready is not a function

If you develop a website using jQuery with other JavaScript libraries (such as mootools, scriptaculous, etc.) on the same page, you may receive this error message while debugging the page (using firebug):

$ is not a function
$(document).ready(function(){ … (line xxx)

or
$().ready is not a function
or
jQuery : Error: $(document).ready is not a function
(document).ready is not a function

Cause

The error occurs because jQuery is conflicting with the other JavaScript libraries on the page. The other library has already overwritten the $() shortcut for jQuery.

Solution

The best workaround is to wrap the function into this anonymous JavaScript function:

( function($) {
	// code goes here 
} ) ( jQuery );

With this function, we are setting $ as a parameter so $ will overwrite any globally defined variables/references of $ in that particular anonymous function. This allows the use of $ within this function without conflicting with other JavaScript libraries. Let’s see an example below:

This is a sample snippet code that will cause the error similar as above.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/scriptaculous/1.8.3/scriptaculous.js" type="text/javascript"></script>
 
<!-- Assume "$" is a prototype reference. This will cause error. -->
<script type="text/javascript">
	$(document).ready(function() {
		$().UItoTop({ easingType: 'easeOutQuart' });
	});
</script>

To solve the error, wrap the function inside the anonymous JavaScript function:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/scriptaculous/1.8.3/scriptaculous.js" type="text/javascript"></script>
 
<!-- Assume "$" is a prototype reference. -->
<script type="text/javascript">
	( function($) {
		<!-- Here "$" is a jQuery reference -->
		$(document).ready(function() {
			$().UItoTop({ easingType: 'easeOutQuart' });
		});
	} ) ( jQuery );	
</script>

Понравилась статья? Поделить с друзьями:
  • Document error on element type raw program and name value true
  • Doctype must be declared first ошибка
  • Doctype must be declared first как исправить
  • Doctype html как исправить
  • Doctype html error