Image width keeps track of zero on load while caching

I am creating a Javascript shortcut and I am trying to adjust the size after loading the image. I use the code below that works fine - it outputs the correct width after loading.

My problem:

When I update, it instantly loads the image from the cache and seems to bypass the load. I get instant zero for width. Why is this happening?

My code is:

var oImage = new Image(); oImage.src = 'http://mydomain.com/image.png'; container.html(oImage); oImage.onload = function(){ alert(this.width); } 

** Update **

@Alex: This is the code I tried with your plugin, I assume that I'm probably doing something wrong. I would like to get this working because your plugin looks pretty good.

 container.waitForImages(function() { var cWidth = $(this).width(); alert("width: "+cWidth); // returns 0 - works first time but not cached }); // Adding the image to the container for preload container.html('<img src="mygraphic.png" />'); 
+4
source share
3 answers

You need to do a few things ...

  • Check the complete property of the img element.
  • Attach the load event before setting the src property.

Also, I found creating a new Image and assigning src , this is the best way to determine if an image is loaded or not.

+4
source

You can switch the calls to .html() and .onload() .

If the image is loaded from the cache, I assume that the .html() call completes before the script was able to associate the function handler with the onload event image, therefore, bypassing the loading event itself (since the image is already loaded ).

If it is still loading the image (i.e. not cached), there will be enough time to call .onload attach before the image completes rendering.

While you're on it, you can do it in a jQuery way, so you add events more like DOM2 than DOM0.

 var image = $('<img/>', { src : 'http://mydomain.com/image.png' }).load(function () { alert(this.width); }) // maybe clear container before if you want .appendTo(container); 

If we need to install src after onload , we could also do this instead:

 var image = $('<img/>') .load(function () { alert(this.width); }) .attr('src','http://mydomain.com/image.png') .appendTo(container) ; 

Hope this works cleanly.

+3
source

This javascript answer : to know when the image is fully loaded allows you to set onload before installing src

+1
source

Source: https://habr.com/ru/post/1393298/


All Articles