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

标签 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>

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

最佳答案

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

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

这将解释如何在 window.alert('alert 2')

之前调用 window.alert('alert 3')


// 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 );
}

以下堆栈片段应重现 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();
}

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


编辑、更新

为了确保函数在 .ready() 处的执行顺序,您可以从函数调用返回一个 promise ,在单个 中使用 .then() .ready() 调用以调用全局或以前在 .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>

关于javascript - jQuery的函数$(function())在$(function())多次调用时的执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39786050/

相关文章:

javascript - 如何测试 jQuery 3.0 beta 是否在浏览器中兼容 Promises/A+?

javascript - jQuery 3.x 中的 jqXHR 对象是否仍支持 .done 方法?

php - 使用 javascript 的简单 php 网站

javascript - 是否可以将 javascript 中的文本缩短为 php get 请求?

javascript - 如何从 jsonp 响应中获取值并将该值设置为其他函数中的其他变量?

javascript - 使用 HTML5 播放器时使用 Javascript 更改 Youtube 视频

javascript - jQuery 3.0 promise

javascript - 如何从代码隐藏但仅在页面加载后执行javascript函数

javascript - 如何将搜索结果显示为 "Showing 1-10 of 300"

javascript - 根据选择框的值隐藏div