alecswan alecswan - 1 year ago 73
jQuery Question

First failing jQuery.ready() breaks the rest

We allow users to write code which sometimes calls

multiple times. It seems like the first function call that throws an error prevents execution of the rest of the functions.

There was a discussion about this here with the solution wrapped
in a delegate instead of wrapping the anonymous function parameter passed to

How can I override
and wrap the passed-in function parameter in a delegate which wraps it in try/catch and the passes to

Here is an example:

// here is some code from third-party developer that sometimes throws an error
jQuery.ready(function() {
if ((new Date()).getMonth() == 0)
throw Error("It's January!");

// here is my code which should run regardless of the error in the <head> script
jQuery.ready(function() {
alert("I need to run even in January!");

What can I do to make code in run regardless of errors in ?

Answer Source

If you need to catch your own errors, then catch them with your own try/catch:

$(document).ready(function() {
   try {
       // put your normal code here
   } catch (e) {
       // put any code you want to execute if there's an exception here

This will allow all subsequent code to continue without pause. One might ask why you're getting errors thrown? And perhaps what you should be doing to fix that or handle that more directly?

If you want, you could do this and replace all the troublesome calls to jQuery.ready() with jQuery.safeReady():

jQuery.fn.safeReady = function(f) {
    jQuery.ready(function() {
        try {
        } catch(e) {
            // make it so you can see errors in the debugger 
            // so you would know if something was wrong
            if (window.console) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download