How to continue javascript execution when getting errors during loading

Not sure what the best way to formulate the question is, but suppose you use jQuery to configure various things, for example:

<script> function doSecond(){ alert("Hi"); } function dofirst(){ var x = asdasd; } $(dofirst); $(doSecond); </script> 

So imagine dofirst and dosecond are completely independent. If dofirst throws an exception, which of course will be, then doSecond never fires. I understand why this is happening, but I wonder if there is a way around this without having to wrap EVERY kind of jQuery handler that I want to configure in a try catch. For example, I would rather not do:

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

Now, if you are wondering why I want to do this? Well, take, for example, the code on the page you are 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 for some dom elements to disappear when you click on them? Not. But if you make a mistake in this function, then it is quite possible that another javascript that you really need to run may never get the setting.

+4
source share
2 answers

Several ways to ensure that everything works independently of each other:

  • Like you said try / catch every

  • Call each one in setTimeout (or whatever jQuery syntax sugar is for this)

  • Separate into different <script> blocks

+1
source

Obviously, never throwing an exception is a ridiculous suggestion. Especially in the world of many browsers / versions / up servers / servers. There are so many ways a JS website can crash it hard to find a site of any size that does not throw an exception of any type (in the console exam).

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

 function safeonload(fn){ $(function(){ try{ fn(); }catch{ //log? } }); } safeonload(doFirst); safeonload(doSecond); 
+1
source

All Articles