For the first question Why window.load event occurs before img is loaded? :
It doesn't. According to your output screenshot, you clearly got values for .height()
and .width()
methods. Which does mean that either the image has loaded, or that your image have its height/width set by CSS.
For the second question, in vanilla javascript, it could be written as
document.querySelector('#div1').innerHTML = "Height= " +
parseFloat(getComputedStyle(document.querySelector('#img1')).height) + "<br>" +
"width= " + parseFloat(getComputedStyle(document.querySelector('#img1')).width);
As you can see in jquery's docs, width()
and height()
methods, both return the "the current computed" width/height.
So if your image wasn't loaded yet, these methods would return 24
, which is the size of the default not found
icon or 0
.
var before = "before load height= " + jQuery('#img1').height() + "<br>" + "before load width= " + jQuery('#img1').width()+"<br>";
jQuery(window).load(function() {
jQuery('#div1').html(before + "on load height= " + jQuery('#img1').height() + "<br>" + "on load width= " + jQuery('#img1').width());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1"></div>
<img id="img1" src="http://lorempixel.com/200/200">
Now, my guess is that you are wondering why the text is written on top of the image, when you asked javascript to write it after the image has loaded.
Then the answer is simply that you are writing into the <div id="div1"></div>
which is placed before the <img>
tag in you html. The time js is executed has no importance on how the content will be rendered, if you tell the browser to place an element as the first node, ( and if you only use default CSS ) then it will be at top of your page.
" + "width= " + getComputedStyle(document.querySelector('#img1')).width;` and maybe your problem nb 1 is that the `width()` and `height()` methods do return the computed style, not the width or height of your images, and that your call to the `alert` method may block the rendering. Try to get `$('#img1')[0].width` instead. – Kaiido Dec 26 '15 at 03:28