jQuery中的$(window).load(function(){})和$(document).ready(function(){})有什么区别?


当前回答

$(document).ready(function() {
 // executes when HTML-Document is loaded and DOM is ready
 alert("document is ready");
});


$(window).load(function() {
 // executes when complete page is fully loaded, including all frames, objects and images
 alert("window is loaded");
});

其他回答

<html>
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script>
    $( document ).ready(function() {
        alert( "document loaded" );
    });

    $( window ).load(function() {
        alert( "window loaded" );
    });
    </script>
</head>
<body>
    <iframe src="http://stackoverflow.com"></iframe>
</body>
</html>

窗口。加载将在所有iframe内容加载后触发

$(document).ready(function() {
 // executes when HTML-Document is loaded and DOM is ready
 alert("document is ready");
});


$(window).load(function() {
 // executes when complete page is fully loaded, including all frames, objects and images
 alert("window is loaded");
});

jQuery 3.0中$(window).load()不可用

$( window ).load(function() {
        // Handler for .load() called.
});

为了解决这个问题,你可以使用它作为“事件处理程序附件”

$( window ).on("load", function() {
        // Handler for .load() called.
});

文档。ready是一个jQuery事件,它在DOM准备好时运行,例如,所有的元素都在那里可以找到/使用,但不一定是所有的内容。 窗口。Onload在图像等加载时稍后触发(或在最坏/失败的情况下同时触发),因此如果您正在使用图像尺寸,您通常会使用此方法。

根据DOM Level 2 Events, load事件应该在文档上触发,而不是在窗口上。但是,为了向后兼容,所有浏览器都在window上实现加载。