New Image (), how do I know if an image is 100% loaded or not?

I create a new image using

img = new Image();
img.src = image_url;

Then I assign img.src to the img src tag in the DOM

$("#my_img").attr("src", img.src);

How to find out that img.src is 100% loaded? What is the best practice? img.completeIt seems to me that in some browsers there are few errors.

So, in other words, I need to assign img.srcto $("#my_img")only after img, it was 100% loaded.

Thank!

+26
source share
2 answers

Use the event load:

img = new Image();

img.onload = function(){
  // image  has been loaded
};

img.src = image_url;

Also see:

+48
source

Using the Promise Template:

function getImage(url){
        return new Promise(function(resolve, reject){
            var img = new Image()
            img.onload = function(){
                resolve(url)
            }
            img.onerror = function(){
                reject(url)
            }
            img.src = url
        })
    }

And when calling a function, we can handle its response or error quite accurately.

getImage('imgUrl').then(function(successUrl){
    //do stufff
}).catch(function(errorUrl){
    //do stuff
})
+7

All Articles