jQuery's function $(function())的执行顺序当$(function())被多次调用时

jQuery's function $(function())’s execute order when the $(function()) called more one times

本文关键字:function 顺序 调用 jQuery 执行      更新时间:2023-09-26

如下代码:

$(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>

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

39303947行,jQuery版本3.1.1处理.ready()document已经加载后被调用。在第3938行jQuery.readysetTimeout内部调用,没有设置持续时间,附加注释

// 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

描述的结果

<!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>

参见3924completed函数

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

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


编辑,更新

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

<!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>