Invalid problem and solution for onload event of image in IE

  • 2020-03-30 03:12:36
  • OfStack

In web development, it is very normal to get the width and height of the image. Before the image is loaded, the width and height of the image cannot be obtained. After the load is completed, the width and height of the image itself can be obtained, for example:


var img = new Image();
img.src = "loading.gif";
img.onload = function(){
 alert ( img.width );
};

OK? This code looks fine, but there is a bug in ie, which is that the first time ie is open, it is fine, the second time you use this method is tragic, ie did not respond, even if the page refresh is the same. Because IE will cache the image, the second load of the image, not from the server, but from the buffer load.
Write the onload method first, then specify the URL of the image, and it will work. So, it's not that IE didn't trigger the onload event, but that the onload event was triggered when the buffer was loaded too fast to run to img.onload. That's OK.


Related articles: