Difference between $(window).load() and $(document

2018-12-31 15:46发布

What is the difference between $(window).load(function() {}) and $(document).ready(function() {}) in jQuery?

标签: jquery
12条回答
临风纵饮
2楼-- · 2018-12-31 16:09

The $(window).load() is NOT available in jQuery 3.0

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

To get around it, you can use it as an "Event Handler Attachment"

$( window ).on("load", function() {
        // Handler for .load() called.
});
查看更多
残风、尘缘若梦
3楼-- · 2018-12-31 16:10

The difference are:

$(document).ready(function() { is jQuery event that is fired when DOM is loaded, so it’s fired when the document structure is ready.

$(window).load() event is fired after whole content is loaded.

查看更多
长期被迫恋爱
4楼-- · 2018-12-31 16:12
<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>

window.load will be triggered after all the iframe content is loaded

查看更多
人气声优
5楼-- · 2018-12-31 16:12

According to DOM Level 2 Events, the load event is supposed to fire on document, not on window. However, load is implemented on window in all browsers for backwards compatibility.

查看更多
余生无你
6楼-- · 2018-12-31 16:16

From jquery prospective - it's just adding load/onload event to window and document. Check this out:

window.onload vs document.onload

查看更多
姐姐魅力值爆表
7楼-- · 2018-12-31 16:16

$(window).load is an event that fires when the DOM and all the content (everything) on the page is fully loaded like CSS, images and frames. One best example is if we want to get the actual image size or to get the details of anything we use it.

$(document).ready() indicates that code in it need to be executed once the DOM got loaded and ready to be manipulated by script. It won't wait for the images to load for executing the jQuery script.

<script type = "text/javascript">
    //$(window).load was deprecated in 1.8, and removed in jquery 3.0
    // $(window).load(function() {
    //     alert("$(window).load fired");
    // });

    $(document).ready(function() {
        alert("$(document).ready fired");
    });
</script>

$(window).load fired after the $(document).ready().

$(window).load was deprecated in 1.8, and removed in jquery 3.0

查看更多
登录 后发表回答