4

Not sure the best way to phrase the question, but suppose you are using jQuery to setup various things like so:

<script>

    function doSecond(){
        alert("Hi");
    }

    function dofirst(){
        var x = asdasd;
    }

    $(dofirst);
    $(doSecond);

</script>

So, imagine that dofirst and dosecond are completely independent. If dofirst throws an exception, which of course it will, then doSecond will never fire. I understand why this happens, but I'm wondering if there is a way of getting around this without having to wrap EVERY kind of jQuery handler that I want to set up in a try catch. E.g., I'd rather not do:

try{
 $(doFirst);
}
catch{
 //maybe log here?
}

try{
 $(doSecond);
}
catch{
 //maybe log here?
}

Now, if you're wondering why I want to do this? Well, take for example the code on the page you're looking at right now:

<script type="text/javascript">
        $(function() {
            $('#title').focus(function() { $('#how-to-tag').hide(); $('#how-to-format').hide(); $('#how-to-title').fadeIn('slow'); });
            $('#wmd-input').focus(function() { $('#how-to-tag').hide(); $('#how-to-format').fadeIn('slow'); $('#how-to-title').hide(); });
            $('#tagnames').focus(function() { $('#how-to-tag').fadeIn('slow'); $('#how-to-format').hide(); $('#how-to-title').hide(); });
        });
    </script>

Is it really necessary to have certain dom elements fade out when you click on them? No. But if you make a mistake in that function, then quite possibly other javascript that you really, really do need to run may never get setup.

2
  • 2
    The best way to do it is to have your code not throw exceptions. Page errors should always be treated as bugs, and fixed. Commented Sep 10, 2010 at 13:55
  • So the best solution is not make mistakes? +1 :) Commented Sep 11, 2010 at 2:21

2 Answers 2

1

A couple of ways to ensure things run independently of each other:

  • As you said, try/catch around each

  • Call each in a setTimeout (or whatever the jQuery syntactic sugar is for that)

  • Separate into different <script> blocks

Sign up to request clarification or add additional context in comments.

Comments

1

Obviously not ever throwing an exception is a ridiculous suggestion. Especially in the world of many browsers/versions/servers up/servers down. There are so many ways of website JS to break it's hard to find a site of any size which doesn't throw an exception of some type (on console examination).

You could create a simple wrapper (or extend existing jQuery methods)

function safeonload(fn){
   $(function(){
     try{
       fn();
     }catch{
        //log?
     }
   });
 }

 safeonload(doFirst);
 safeonload(doSecond);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.