在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 描述的结果
<!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
Line 的功能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()
inside single .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>