I wrote some jQuery code in which I was getting the width of images on screen and storing them in a variable. Then I logged that variable in the console to see it’s value. When the page loads for the first time, it displays correct value, however if I press F5, it displays 0 as the width.
Here’s the HTML:
<body>
<img src="img1.jpg" alt="image">
<img src="img1.jpg" alt="image">
<script type="text/javascript" src="script.js"></script>
</body>
Here’s the jQuery code (script.js) :
jQuery(document).ready(function($) {
var imgs = $('img');
var width = imgs[0].width;
console.log(width);
});
The console displays 600 when the page is loaded for the first time but when I press F5 it displays 0.
Why is it so?
At
jQuery(document).ready()time, there is no guarantee that images are loaded yet. Images must be loaded in order to get their width. Images are loaded asynchronously and may finish afterjQuery(document).ready()fires.To know for sure that an image is loaded, you either need to have an
onloadhandler for that specific image so you can know when it is specifically loaded or you need to only inspect the image widths when all the images in the page are loaded withwindow.onloador in jQuery$(window).load(fn).The simplest thing to do would be to change your code to this:
Personally, I would recommend that you use jQuery’s
.height()and.width()methods like this:You can see this one work here: http://jsfiddle.net/jfriend00/D4CyN/