Image loading does not work with IE 8 or lower

I am trying to check if the image was uploaded successfully. It works well in modern browsers, but IE8 or 7 is a terrible problem. Here is a sample code:

var img = new Image(), url = 'http://something.com/images/something.gif'; $(img).attr('src', url).load(function() { if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) { alert('broken image!'); } else { alert('successfully loaded'); } } 

Anyone have an idea to work with this problem? Thanks at advace!

+6
source share
3 answers

You need to install the onload handler before you set the .src value.

In some versions of IE, if the image is in the browser’s cache, a download event will be fired immediately after setting the .src value. If your load handler is not already installed, you will skip this event.

In addition, naturalWidth and naturalHeight NOT supported in older versions of IE, so they will always be undefined. And you must use onerror and onabort to catch the error conditions.

No need to use jQuery for this. You can simply do this:

 var img = new Image(), img.onload = function() { alert("loaded successfully"); } img.onerror = img.onabort = function() { alert("broken image"); } // only set .src AFTER event handlers are in place img.src = 'http://something.com/images/something.gif'; 
+12
source

If the image is broken, the onload will not be fired, instead the onerror event will be fired. So you need to do the following:

 var img = new Image(), url = 'http://something.com/images/something.gif'; img.onload = function() { alert('successfully loaded'); }; img.onerror = function() { alert('broken image!'); }; $(img).attr('src', url); 

Or using jQuery:

 $(img).load(function() { alert('successfully loaded'); }).error(function() { alert('broken image!'); }).attr('src', url); 
+3
source
 var url="http://something.com/images/something.gif", img=new Image; img.onload=img.onerror=function(ev){ if(ev.type=="load")alert("successfully loaded"); else if(ev.type=="error")alert("error loading"); } img.src=url; // If image is cached then no `onload` or `onerror` can occur. if(img.complete){ alert("successfully loaded"); img.onload=img.onerror=null; } 
+1
source

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


All Articles