1

I have to load image from another site (cross domain)

my question is , i may can check somehow if the image has successfully loaded?

3 Answers 3

6

Typically you would put this in a load event listener like so:

var img = new Image();
img.onload = function(){
    alert(this.src + " loaded");
}
img.src="http://example.com/images/a.png";
Sign up to request clarification or add additional context in comments.

4 Comments

is the new Image() necessary ? if it is -why? if it's not -why?
@MorSela Yes it is necessary. You have to create a new image object, but nothing is loaded at this point. Once you giver it a souce, it starts to load. If you just assign the url, js assumes you just want a string and not an image.
Move the onload function above the setting of the src property - cached images may fire the onload instantly, before the onload event handler is set.
@Greg thank you for that information! I'll change it directly.
0

For Javascript Check this out

http://www.sajithmr.me/javascript-check-an-image-is-loaded-or-not

I know the way aroung with jQuery.

$('#image1')
.load(function(){
    $('#result1').text('Image is loaded!'); 
})
.error(function(){
    $('#result1').text('Image is not loaded!');
});

Comments

0

If you're loading the image in an html tag, you can use the onerror event. For example:

<img src="https://otherdomain.com/img.jpg" onerror="handleImgError();" />

If handleImgError() runs, then you know that the image didn't load properly.

2 Comments

if i don't i can't do something similar in clean js?
You can use the Image object mentioned in the answer by Joseph, and use img.complete, which returns a boolean - true if the browser has completed downloading the image. You can also use the onerror() method, which would be very similar to the HTML shown above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.