jQuery $(document).ready错误阻止页脚脚本

时间:2015-02-17 17:47:18

标签: javascript jquery html wordpress

所以我有一个独特的问题。

我有一个我根本无法编辑模板的网站,我只能改变嵌入式脚本。

此嵌入式脚本将注入相关网站的页脚。

嵌入式脚本依赖于$(document).ready来启动自己。

问题是,页面上方的脚本会在其$(document).ready函数中引发错误,导致我的$(document).ready无法被调用。

我尝试设置try .. catch块,例如this,但我相信只有当我的脚本在页面上更高时才能使用。

我的问题是,是否可以让我的$(document).ready来电运行,即使它在页面上较低,而前一个有错误?

在我的脚本上方的网站中:

<script type="text/javascript">
  jQuery(document).ready(function($) {
    $('#logo').vAlign();
  });
</script>

.vAlign();未定义,因此投掷:Uncaught TypeError: undefined is not a function

在我的嵌入式js中:

jQuery(document).ready(function() {
  console.log('ready!');
});

我从未见过&#34;准备好了!&#34;在控制台中。

2 个答案:

答案 0 :(得分:2)

当必须始终执行重要操作时,可以使用try-catch的代码块。即使catch-codeblock没有通过finally-codeblock运行,所以无论是否存在错误(语法错误除外),最后都会调用 callReady -function。如下所示:

<script language="JavaScript" src="https://code.jquery.com/jquery-1.11.2.js" type="text/javascript"></script>
<script type="text/javascript">

  try{
    jQuery(document).ready(function($) {
      $('#logo').vAlign();
    });
  }
  catch(e){
    console.log(e);
  }
  finally{
    // some fallback code might be executed here
    callReady();
  }


  jQuery(document).ready(callReady);

  function callReady(){
    console.log('ready!');
  }

</script>

不幸的是,如果没有错误 callReady 被调用两次(因为最后总是在最后运行),但你可以检查这种情况:

<script type="text/javascript">

  var errorHappened = true;

  function checkForErrors(callback){

      callback();

      // when interpreter reaches this point no error with business-code is thrown
      errorHappened = false;

  }

  try{
    jQuery(document).ready(function($) {

      try{

        checkForErrors(function(){

            // put business-code in here

            $('#logo').vAlign();

        })


      }
      finally{
        if(errorHappened){
            callReady();
        }
      }

    });
  }
  catch(e){
    console.log(e);
  }


  jQuery(document).ready(callReady);

  function callReady(){
    console.log('ready!');
  }

</script>

答案 1 :(得分:1)

页面中一个脚本标记中的错误不会阻止其他脚本运行。

示例:

<script>
    $(function(){ console.log(1); });
</script>
<script>
    $(function(){ console.log 2; });
</script>
<script>
    $(function(){ console.log(3); });
</script>

这将首先记录第二个脚本标记的语法错误,然后它将记录值1和3,因为其他就绪事件正常工作。

演示:http://jsfiddle.net/Guffa/am4f7f18/