当$(function())调用多次时,jQuery的函数$(function())的执行顺序 [英] jQuery's function $(function())’s execute order when the $(function()) called more one times

查看:81
本文介绍了当$(function())调用多次时,jQuery的函数$(function())的执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这样的代码:



  $(window.document).ready (function(){window.alert('alert 1');}); $(function(){window.alert('alert 2');}); $(function(){window.alert('alert 3 ');});  

 <!DOCTYPE html> < html lang =en>< head> < meta charset =UTF-8> <标题> DEMO2< /标题> < script src =jquery-3.1.1.js>< / script> < script src =demo2.js>< / script>< / head>< body>< / body>< / html>  



当我执行上面的代码时,页面'警报顺序有时是:
alert 1,alert 2,alert 3 ,有时是:警报1,警报3,警报2.
任何人都可以告诉我为什么?

解决方案

At行 3930 通过 3947 jQuery版本3.1.1处理 .ready()文件已经加载后被调用。在第3938行 jQuery.ready setTimeout 内调用,没有设置附加评论的持续时间

  //异步处理它以允许脚本有机会延迟准备

这将解释如何在$ code> window.alert之前调用 window.alert('alert 3') ('警告2')




  //在浏览器事件发生后,将$(document).ready()称为
//的情况。
//支持:IE< = 9 - 10只有
//较旧的IE有时会很快发出交互信号
if(document.readyState ===complete||
(document.readyState!==loading&&!document.documentElement.doScroll)){

//异步处理它以允许脚本有机会延迟准备
window.setTimeout(jQuery.ready); //第3938行

} else {

//使用方便的事件回调
document.addEventListener(DOMContentLoaded,已完成);

//回退到window.onload,总是有效
window.addEventListener(load,completed);
}

以下stacksnippet应该重现OP描述的结果



 <!DOCTYPE html>< html lang =en>< head> < meta charset =UTF-8> <标题> DEMO2< /标题> < script src =https://code.jquery.com/jquery-3.1.1.js>< / script> <脚本> $(window.document).ready(function(){window.alert('alert 1');}); $(function(){window.alert('alert 2');}); $(function(){window.alert('alert 3');}); < /脚本>< /头><主体>< / BODY>< / HTML>  



另请参阅已完成 3924

  //就绪事件处理程序和自清理方法
函数completed(){
document.removeEventListener(DOMContentLoaded,已完成);
window.removeEventListener(load,completed);
jQuery.ready();
}

请参阅plnkr http://plnkr.co/edit/C0leBhYJq8CMh7WqndzH?p=preview






编辑,更新



确保 .ready()的执行顺序你可以从函数调用返回一个promise,在单个 .ready() .then() c>调用全局或以前在 .ready()处理程序中定义的函数。



 <!DOCTYPE html>< html lang =en>< head> < meta charset =UTF-8> <标题> DEMO2< /标题> < script src =https://code.jquery.com/jquery-3.1.1.js>< / script> <脚本> function ready1(wait,index){//做东西返回新的Promise(resolve => {setTimeout(()=> {window.alert('alert'+ index); resolve(index)},wait)}) .then((i)=> console.log(i))} function ready2(wait,index){//做东西返回新的Promise(resolve => {setTimeout(()=> {window.alert( 'alert'+ index); resolve(index)},wait)})。then((i)=> console.log(i))} function ready3(wait,index){//做东西返回新的Promise( resolve => {setTimeout(()=> {window.alert('alert'+ index); resolve(index)},wait)})。then((i)=> console.log(i)) } $()。ready(function(){ready1(3000,0).then(function(){return ready2(1500,1)})。then(function(){return ready3(750,2)}); })< / script>< /他ad>< / html>  


Code like this:

$(window.document).ready(function () {
    window.alert('alert 1');
});

$(function () {
    window.alert('alert 2');
});

$(function () {
   window.alert('alert 3');
});

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo2</title>
    <script src="jquery-3.1.1.js"></script>
    <script src="demo2.js"></script>
</head>
<body>

</body>
</html>

when i execute the above code, the page' alert order sometimes is: alert 1, alert 2, alert 3, and sometimes is: alert 1, alert 3, alert 2. could anyone tell my why?

解决方案

At lines 3930 through 3947 jQuery version 3.1.1 handles .ready() being called after document has already loaded. At line 3938 jQuery.ready is called inside of setTimeout without a duration set with attached comment

// Handle it asynchronously to allow scripts the opportunity to delay ready

which would explain how window.alert('alert 3') could potentially be called before window.alert('alert 2')


// Catch cases where $(document).ready() is called
// after the browser event has already occurred.
// Support: IE <=9 - 10 only
// Older IE sometimes signals "interactive" too soon
if ( document.readyState === "complete" ||
    ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {

    // Handle it asynchronously to allow scripts the opportunity to delay ready
    window.setTimeout( jQuery.ready ); // Line 3938

} else {

    // Use the handy event callback
    document.addEventListener( "DOMContentLoaded", completed );

    // A fallback to window.onload, that will always work
    window.addEventListener( "load", completed );
}

The following stacksnippet should reproduce result described by OP

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Demo2</title>
  <script src="https://code.jquery.com/jquery-3.1.1.js"></script>
  <script>
    $(window.document).ready(function() {
      window.alert('alert 1');
    });

    $(function() {
      window.alert('alert 2');
    });

    $(function() {
      window.alert('alert 3');
    });
  </script>
</head>

<body>

</body>

</html>

See also completed function at Line 3924

// The ready event handler and self cleanup method
function completed() {
    document.removeEventListener( "DOMContentLoaded", completed );
    window.removeEventListener( "load", completed );
    jQuery.ready();
}

See plnkr http://plnkr.co/edit/C0leBhYJq8CMh7WqndzH?p=preview at version 1


Edit, Updated

To ensure the order of execution of functions at .ready() you can return a promise from the function calls, use .then() inside single .ready() call to call functions defined globally or previously within .ready() handler.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Demo2</title>
  <script src="https://code.jquery.com/jquery-3.1.1.js"></script>
  <script>
    function ready1(wait, index) {
      // do stuff
      return new Promise(resolve => {
          setTimeout(() => {
            window.alert('alert ' + index);
            resolve(index)
          }, wait)
        })
        .then((i) => console.log(i))
    }

    function ready2(wait, index) {
      // do stuff
      return new Promise(resolve => {
          setTimeout(() => {
            window.alert('alert ' + index);
            resolve(index)
          }, wait)
        })
        .then((i) => console.log(i))
    }

    function ready3(wait, index) {
      // do stuff
      return new Promise(resolve => {
          setTimeout(() => {
            window.alert('alert' + index);
            resolve(index)
          }, wait)
        })
        .then((i) => console.log(i))
    }
    $().ready(function() {
      ready1(3000, 0) 
      .then(function() {
        return ready2(1500, 1) 
      })
      .then(function() {
        return ready3(750, 2) 
      });
    })
  </script>
</head>

</html>

这篇关于当$(function())调用多次时,jQuery的函数$(function())的执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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