首先失败的jQuery.ready()打破了其余部分

ale*_*wan 10 error-handling jquery

我们允许用户编写有时会jQuery.ready(function(){..})多次调用的代码.看起来第一个抛出错误的函数调用会阻止执行其余的函数.

这里讨论了这个问题,解决方案包含jQuery.ready()在委托中,而不是包装传递给的匿名函数参数jQuery.ready(..).

如何jQuery.ready(fn)在委托中覆盖和包装传入的函数参数,该委托将其包装在try/catch中并传递给jQuery.ready(delegate)

这是一个例子:

<head>
  <script>
    // 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!");
    });
  </script>
</head>

<body>
  <script>
    // 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!");
    });
  </script>
</body>
Run Code Online (Sandbox Code Playgroud)

无论错误是什么,我该怎么做才能使代码运行?

jfr*_*d00 7

如果您需要捕获自己的错误,请使用您自己的错误捕获它们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
   }
});
Run Code Online (Sandbox Code Playgroud)

这将允许所有后续代码继续而不会暂停.有人可能会问你为什么会被抛出错误?也许你应该做些什么来解决这个问题或者更直接地处理它?

如果你愿意,你可以做到这一点,并更换所有的麻烦来电jQuery.ready()jQuery.safeReady():

jQuery.fn.safeReady = function(f) {
    jQuery.ready(function() {
        try {
            f();
        } catch(e) {
            // make it so you can see errors in the debugger 
            // so you would know if something was wrong
            if (window.console) {
                console.log(e);
            }
        }
    });
};
Run Code Online (Sandbox Code Playgroud)