问题描述
如该线程中所述: window.onload与$(document).ready(). window.onload
应该晚于$(document).ready()
发生,但是在此简单代码中,日志将显示onload
事件是在ready事件之前执行的吗?我在这里想念什么?
As stated in this thread: window.onload vs $(document).ready(). The window.onload
should occur later than the $(document).ready()
but in this simple code the log would show that the onload
event is executed before the ready event? What I'm I missing here?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<h1>A Simple Site</h1>
<script>
$(document).ready(function() {
console.log("ready event fired");
})
window.onload = function() {
console.log("onload event fired");
}
</script>
</body>
</html>
推荐答案
问题不在于事件的顺序.它与围绕本机DOM事件的jQuery包装器一起使用.如果尝试使用本机DOMContentLoaded
,则会发现它始终在window.onload
之前运行.但是jQuery事件$(document).ready
将在DOMContentLoaded
之后几毫秒,在某些情况下也可能在window.onload
之后,尤其是如果页面没有太多加载(如下面的代码)时.延迟是由于jQuery的实现.
The problem is not with the order of the events. It with the jQuery wrapper around the native DOM events. If you try the native DOMContentLoaded
you will find that it always runs before window.onload
. But the jQuery event$(document).ready
will come some milliseconds after DOMContentLoaded
, which in some cases might be after window.onload
too, especially if the page doesn't have much to load like the code below. This is delay is due to jQuery implementation.
但是,如果您取消注释代码中的iframe,则加载会花费一些时间,这会导致window.onload
延迟,因此$(document).ready
将排在第一位.
If you uncomment the iframe in the code though, it takes some time to load which causes the window.onload
to be delayed, so $(document).ready
will come first.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<h1>A Simple Site</h1>
<!-- <iframe src="http://stackoverflow.com"></iframe> -->
<script>
$(document).ready(function() {
console.log("jQuery ready");
})
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM ready");
});
window.onload = function() {
console.log("DOM loaded");
}
</script>
</body>
</html>
这篇关于为什么window.onload事件在$(document).ready之前发生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!