处理jQuery(document).ready中的错误

问题描述:

我正在开发用于Web框架的JS,并经常与其他开发人员(通常容易出错)的jQuery代码混合使用。不幸的是,他们的jQuery(文档).ready块中的错误阻止了我的执行。采取以下简单示例:

I'm developing JS that is used in a web framework, and is frequently mixed in with other developers' (often error-prone) jQuery code. Unfortunately errors in their jQuery(document).ready blocks prevent mine from executing. Take the following simple sample:

<script type="text/javascript">
    jQuery(document).ready(function() {
        nosuchobject.fakemethod();       //intentionally cause major error
    });
</script>
<script type="text/javascript">
    jQuery(document).ready(function() {
        alert("Hello!");                 //never executed
    });
</script>

不管先前发生了什么,第二个就绪块不应该执行吗?是否有一种安全的方式来运行jQuery(document).ready即使出现以前的错误也会运行?

Shouldn't the second ready block execute regardless of what happened in the previous? Is there a "safe" way to run jQuery(document).ready that will run even in the case of previous errors?

编辑:我没有控制/可见性容易出错的块,因为它们是由其他作者编写的并且是任意混合的。

I have no control/visibility over the error-prone blocks as they're written by other authors and mixed in arbitrarily.

我还没试过这段代码,但它应该工作(至少,这个想法应该是)。 确保在jquery之后包含它,但是在任何潜在的错误脚本之前。(没必要,请参阅注释。)

I haven't tried this code, but it should work (at least, the idea should anyway). Make sure you include it AFTER jquery, but BEFORE any potentially buggy scripts. (Not necessary, see comments.)

var oldReady = jQuery.ready;
jQuery.ready = function(){
  try{
    return oldReady.apply(this, arguments);
  }catch(e){
    // handle e ....
  }
};