0

I have made a little plugin where I get the size using naturalHeight and naturalWidth

Sometimes when loading page I get 0 in width and height (other times it works fine). I guess it is because it calculate the size before loading the image.

How can I correct this?

I have tried to run plugin $("selector").myplugin() inside $(document).ready, but that doesn't change anything

I have also tried to wrap setTimeout around the variables where I am using naturalHeight and naturalWidth, but that doesn't prevent rest of the code to run - and I won't make it slower loading than necessary (wrap everything in setTimeout if not necessary)

So my question - are there a way to

  1. if size is 0 - wait a little and try again
  2. Not continue running rest until it is not 0 anymore

Or does anyone have another solution?

Bourbia Brahim
  • 14,459
  • 4
  • 39
  • 52
Mik2000dk
  • 31
  • 3
  • 1
    If your script needs to run after the images have been loaded you should be using `$(window).load()` rather than `$(document).ready()` – Turnip Mar 29 '18 at 13:35
  • 1
    Use the `onload` event on your `img` elements, and here is some ways: https://stackoverflow.com/questions/623172/how-to-get-image-size-height-width-using-javascript – Asons Mar 29 '18 at 13:37

1 Answers1

0

Ready wait only for dom to be loaded , You can use the load() on your image in order in this case , you'll not wait till all the window elm are loaded

See below snippet after loading image , The size of this last is being printed on the bottom ,

$(function(){
  $( "#img" ).load(function() {
    console.log($(this).width()+"-"+$(this).height())
  });
    
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="img" src="https://cdn.pixabay.com/photo/2017/09/07/14/15/wide-2725426_960_720.jpg" >
Bourbia Brahim
  • 14,459
  • 4
  • 39
  • 52