How to continue javascript execution when receiving errors during load
Not sure the best way to phrase the question, but suppose 开发者_JAVA技巧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.
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
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);
 加载中,请稍侯......
      
精彩评论