我也在这里解释得很清楚:
https://discuss.codecademy.com/t/window-onload-vs-document-ready/19000
当我说:
jQuery document.ready会在HTML全部准备好但图片和其他资源尚未完成时运行您的代码。这是您可以使用JavaScript更改DOM的最早可能时间,因此它被广泛使用。在现代浏览器(如Google Chrome)中,它被DOMContentLoaded3替换。再次了解更多信息。
$document.ready(fn)将在交互式界面开始时加载,当Dom“完成”加载时...
n = -1;
function ready() {
document.getElementsByTagName("p")[0].textContent += "ready " + ++n + "\n";
}
$(document).ready(ready);
$(document).ready(function() {
ready();
$(document).ready([function() {
ready()
},
function() {
$(document).ready(function() {
ready();
$(document).ready([
function() {
ready()
}, function() {
ready()
if (n === 5) $(document).ready(function() {ready()})
}]);
})
}
])
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<body>
<p></p>
</body>
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 );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed );
}
ready
不是$(document).ready()
中的事件名,而是一个包装函数吗? - overexchange