0

I load a lot of images to my site and it works fine if I'm patient. But sometimes I fire an action with myDiv.style.display = 'none'; in it during image load and then the image gets width=height=0, for all the images haven't been completed. When I make my div visible again I can't see them but identify by searching for width=height=0.

If I set the width and height to something bigger than 0, I see the images but in this way I lose the real size. I also tried to change image.src by adding something like myImage.src += "?t=random";. Doing this, myImage.onload function gets fired again but width and height are still 0.

How can I get the real size of the images or how can I force a reload?

Drew Gaynor
  • 8,292
  • 5
  • 40
  • 53
TJB
  • 1
  • 1
    It sounds like your myImage.src isn't being executed and that you have an empty image tag as a result. Are you getting any errors when you run it? – ctwheels Aug 01 '14 at 17:02

2 Answers2

1

You can attach an event to your image elements:

image.onload = function () { /* Your code here */ };

This will fire when the image is actually loaded.

Make sure this event is attached before you set the src element and make sure that your src is actually valid. You can check this in the Network panel in Google Chrome (F12 on Windows).

Ivan
  • 10,052
  • 12
  • 47
  • 78
  • Can you reproduce the problem in jsfiddle or a small subset of code? – Ivan Aug 01 '14 at 17:09
  • The critical point is, that to reproduce it I have to fire a function which sets the div to unvisible before the image load has finished. If I wait till each image has loaded everything works fine. – TJB Aug 01 '14 at 17:15
0

Taking a deeper look i found following Workaround.

When the image is loaded the first time, it has a valid width and height but doesn't get painted because of the div is not visible. When I make the div visible again and initiate the reload by changing the image URL like myImage.src+="?t=random" the image.onload gets fired with the image width and height of 0. So what I can do is just to save the original values and use them if needed.

// save or reload image size in case of load interruption if (typeof this.orgWidth == 'undefined' && this.width>0) this.orgWidth = this.width; if (typeof this.orgHeight == 'undefined' && this.height>0) this.orgHeight = this.height; if (this.width==0) this.width=this.orgWidth; if (this.height==0) this.height=this.orgHeight;

TJB
  • 1