处理jQuery(document).ready中的错误 [英] Handling errors in jQuery(document).ready

查看:101
本文介绍了处理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 ....
  }
};

这篇关于处理jQuery(document).ready中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆