首页 > jquery如何接管ready事件?

jquery如何接管ready事件?

我要做了某些事情(例如等待某个浏览器插件就绪)后才触发ready事件,请问如何实现?


把你那些要绑定在 ready 时执行的事件, 绑定到 html 上面的某个自定义事件上,
然后在你要触发的时候使用$('html').trigger('自己定义的事件名');.

<!doctype html>
<html lang="en">
<head>
  <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body>
    <script>

    $('html').on('customEvent', function(){
      alert(1);
    });

    $('html').on('customEvent', function(){
      alert(2);
    });


    //模拟 某个浏览器插件就绪 所需要的延时
    setTimeout(function(){
      $('html').trigger('customEvent');
    }, 2000);

    //如果要还原为在ready时触发,使用下面这样的代码
    /*
    $(function(){
      $('html').trigger('customEvent');
    });
    */

    </script>
</body>
</html>

jquery中已经提供了这种延迟触发ready的方式。

我们先来看一个正常顺序执行的例子:

javascriptsetTimeout(function(){
    console.log('timeout');
}, 500);

$(function(){
    console.log('ready');
})

这个例子中,肯定会首先输出ready,然后再输出timeout。

不过jquery提供了一个$.holdReady()方法来延迟ready的触发。

javascriptsetTimeout(function(){
    console.log('timeout');

    // 不用再hold住ready方法了,释放,则现在触发ready方法
    $.holdReady(false);
}, 500);

// 先把readyhold住,不让ready触发,$.holdReady(true)没有位置的限制,可以放到最上面
$.holdReady(true);
$(function(){
    console.log('ready');
})

不过如果有多个组件(比如10个的话)都加载完成再触发ready的话,那是不是要写10个$.holdReady(true)呢。其实不用的,可以用$.readyWait来操作。把$.readyWait的值设置为限制的次数+1就行。如:

javascriptsetTimeout(function(){
    console.log('timeout0');
    $.holdReady(false);
}, 500);
setTimeout(function(){
    console.log('timeout1');
    $.holdReady(false);
}, 500);
setTimeout(function(){
    console.log('timeout2');
    $.holdReady(false);
}, 500);

$.readyWait = 4;
$(function(){
    console.log('ready');
})

这样就能在三个setTimeout都执行完成后再执行ready。其实$.holdReady()在源码也是操作的$.readyWait的值,$.holdReady(true)让$.readyWait的值+1,$.holdReady(false)让$.readyWait的值-1,当$.readyWait的值为1时就触发ready。$.readyWait的默认值是1,所以默认会直接触发ready的。

不过,这样直接使用$.readyWait不是很好,因为$.readyWait是对内使用的,对外提供的方法就是$.holdReady()。因此,若没有特别的情况,使用$.holdReady()就能控制ready的执行了。

【热门文章】
【热门文章】