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

2023-12-24

代码如下:

$(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="https://unpkg.com/[email protected] /cdn-cgi/l/email-protection/dist/jquery.js"></script>
    <script src="demo2.js"></script>
</head>
<body>

</body>
</html>

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


在行3930通过3947jQuery 版本 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 描述的结果

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

也可以看看completed线路功能3924

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

参见 plnkrhttp://plnkr.co/edit/C0leBhYJq8CMh7WqndzH?p=preview http://plnkr.co/edit/C0leBhYJq8CMh7WqndzH?p=preview在版本 1 中


编辑、更新

确保函数的执行顺序.ready()您可以从函数调用返回一个承诺,使用.then()内单.ready()call 调用全局或之前定义的函数.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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

jQuery 函数 $(function()) 多次调用 $(function()) 时的执行顺序 的相关文章