当$(function())调用多次时,jQuery的函数$(function())的执行顺序

时间:2016-09-30 07:31:53

标签: javascript jquery jquery-3

这样的代码:



$(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>
&#13;
&#13;
&#13;

当我执行上面的代码时,页面&#39;警报顺序有时是: 警报1,警报2,警报3,有时是:警报1,警报3,警报2。 谁能告诉我为什么?

1 个答案:

答案 0 :(得分:2)

在第3930行到3947时,jQuery版本3.1.1处理.ready()已加载后调用document。在第3938行,jQuery.ready内部调用了setTimeout,没有设置附加注释的持续时间

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

这将解释在window.alert('alert 3')

之前如何调用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 );
}

以下stacksnippet应该重现OP

描述的结果

&#13;
&#13;
<!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>
&#13;
&#13;
&#13;

另请参阅第completed

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

请参阅第1版的plnkr http://plnkr.co/edit/C0leBhYJq8CMh7WqndzH?p=preview

修改,更新

为了确保.ready()处的函数执行顺序,您可以从函数调用中返回一个promise,在.then()调用中使用.ready()来调用全局或之前定义的函数.ready() {1}}处理程序。

&#13;
&#13;
<!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>
&#13;
&#13;
&#13;