Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(window).on("load") gets executed before $(document).ready. Shouldn't ready be executed first?

Tags:

html

jquery

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="jquery-3.3.1.js"></script>
    <script>
        $(document).ready(function(){
            var h = $("#im").height();
            alert("Hello from ready. Height is " + h);
        });
        $(window).on("load", function(){
            var h = $("#im").height();
            alert("Hello from load. Height is " + h);
        });

    </script>
</head>
<body>
    <p class="" id="msg"></p>
    <p class="" id="msg2"></p>
    <img id="im" src="flower.jpg" alt="">

</body>
</html>

1) The above is my code. When I run this in Chrome 64 (64 bit). The window.load portion gets executed before document.ready.

2) Secondly, based what I have read on these forums and elsewhere on the net, I should not be able to get the image height from document.ready, and yet, it works and I get the same height from both the functions.

Why is this happening?

like image 972
VRM Avatar asked Jun 24 '26 01:06

VRM


1 Answers

jQuery's ready event is first processed by its Deferred implementation, which internally uses setTimeout (probably to allow $.holdReady to function). It's essentially this:

document.addEventListener('DOMContentLoaded', function() {
    setTimeout(function() {
        // Your `ready` callback
    }, 0);
});

Using setTimeout(..., 0) can delay the execution of your callback enough to allow the load event to run its callback first if your page is simple enough. I tested it on Chrome 64.0.3282.186 and the jQuery ready event fired before load only about 10% of the time.

If you use document.addEventListener directly, your code works as expected.

like image 145
Blender Avatar answered Jun 27 '26 00:06

Blender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!