PDA

View Full Version : Is there a way to check loaded-ness when you change the src of an image?



jlizarraga
11-22-2008, 12:36 AM
Hi all,

Is there a way to change the src of an image, then delay a follow-up function from running until the new src is completely loaded?

Any tips greatly appreciated!

jlizarraga
11-22-2008, 02:59 AM
Say you have an image, like so:


<img id="someImage" src="/images/some-image.jpg" alt="Some Image" />

And you change its src with JS, like so:


var oIMG = document.getElementById("someImage");
oIMG.src = "/images/some-other-image.jpg";

Is there a way to tell when the new src has completely finished loading?

magicyte
11-22-2008, 04:38 AM
No. Sorry to say, but this is the only answer to your question. Now, (this is out of the question) you can preload images, but that is probably not what you wanted...

Anywho, no is all I know of. There may be some really complexed and expensive way (in computer terms), and of course, you probably wouldn't want to use it. Heck, I couldn't even code something like that...is this that you need/want important?

-magicyte

jlizarraga
11-22-2008, 09:14 AM
What about this?

http://www.thefutureoftheweb.com/blog/image-onload-isnt-being-called

Can I wait for onload to fire for the image object, then change the existing image's src?

jlizarraga
11-22-2008, 09:35 AM
Nevermind, someone on another forum gave me the solution:


var oIMG = document.getElementById("someImage");
oIMG.addEventListener("load", oIMGloaded, false);
oIMG.src = "/images/some-other-image.jpg";

function oIMGloaded() {
alert("oIMG loaded");
}

jscheuer1
11-22-2008, 09:39 AM
There are two ways I know of to check if an image has loaded. One is to test the complete property of the image object (most useful with preloading of the form of var myImage = new Image()), the other is to await the firing of the onload event of the image tag, which I believe may also work with image objects.

However, the onload event of the image tag is not valid in HTML, so should be assigned via javascrpt. This must be done before setting its source.

To answer your original question, given:


<img src="some.gif" id="theimg">

and:


function whatever (){
do something here when the image has loaded
}

You could do like:


document.getElementById('theimg').onload = whatever;
document.getElementById('theimg').src = 'another.gif';

jlizarraga
11-23-2008, 01:21 AM
Thanks for the responses you guys.