2
<!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?

VRM
  • 151
  • 2
  • 11
  • Is there something wrong with being able to get the image height? I can't imagine how this can possibly count as an error. Also, clear your cache. The browser might be able to tell image properties of cached images straight-away. I'm sure that *"`load` happens before all images have finished loading"* does not mean *"when `load` happens, we guarantee that **no** images have finished loading"*. – Tomalak Feb 28 '18 at 08:41

2 Answers2

8

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.

Blender
  • 289,723
  • 53
  • 439
  • 496
2

Solution 1

Get image info after window is loaded or add an eventListener to the image.

$(window).on('load', function() {/*Do Stuff*/}

or

$('#image').on('load', function() {/*Do Stuff*/}

Here is the solution of your question on Codepen.

Solution 2

True, when document is ready only the structure is loaded, instead, window is loaded all components including images and more is ready and loaded.

More: StackOverflow

Hope this helps.

Carlo Corradini
  • 2,927
  • 2
  • 18
  • 24