469,317 Members | 1,915 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,317 developers. It's quick & easy.

javascript: check if image src exists

Plater
7,872 Expert 4TB
I have seen a lot of pre-loading scripts and none of them seem to help with my problem.

Let's say I have a list of images:
"image1.jpg"
"image2.jpg"
"image3.jpg"

And all the pictures hosted at both:
http://mydomain.com/images/
http://mydomain2.com/images/

I would like to attempt to load pictures from:
http://mydomain.com/images/
and if they fail, get them from the mirror site.

It is acceptable that if one image cannot be found on the first location, to bypass it and get ALL the images from the second location.


Originally I had something like this:
Expand|Select|Wrap|Line Numbers
  1. <img src="http://mydomain.com/images/image1.jpg" onerror="this.src='http://mydomain2.com/images/image1.jpg'" />
  2.  
However, that seems to be a no-no for standards, not to mention causes an infinite loop if the image can also not be found at the second location.

It was recomended that I switch to useing javascript to pre-load the images, but I couldn't find anything in the DOM about detecting if there was an error loading or not.

Does anyone have any ideas for how to detect if the location given to .src can be found?
Nov 27 '07 #1
15 41899
acoder
16,027 Expert Mod 8TB
Try using the complete property. You could use setInterval/setTimeout to make a check that the image has loaded after a period of time.
Nov 27 '07 #2
Plater
7,872 Expert 4TB
Try using the complete property. You could use setInterval/setTimeout to make a check that the image has loaded after a period of time.
I saw the complete property, and saw that IE/FF/opera have it, but that it wasn't part of the standards so I didn't look into it any more.
Would you say it would be safe to do so?

So I tried using it:
Expand|Select|Wrap|Line Numbers
  1. function ImgLoad(sSrc)
  2. {
  3.    var oImg=new Image;
  4.    oImg.src="http://mydomain.com/images/"+sSrc;
  5.    if(oImg.completed)
  6.    {
  7.       return oImg.src;
  8.    }
  9.    else
  10.    {
  11.       return "http://mydomain2.com/images/"+sSrc;
  12.    }
  13. }
  14.  
However, it seems that the .src call doesn't block so it will always show "completed" as false?
Nov 27 '07 #3
acoder
16,027 Expert Mod 8TB
No, the property is called "complete" and you use it on the Image object, not on its source.
Nov 27 '07 #4
Plater
7,872 Expert 4TB
No, the property is called "complete" and you use it on the Image object, not on its source.
Yeah i checked that and fixed it.
It still is always false.
I even tried putting in a while loop to wait for it, waits a looong time, get the "script stopped working" notification...then it works fine everytime?

On a side note, I'm getting REALLY tired of having to use the taskmanager to close FF....
Nov 27 '07 #5
acoder
16,027 Expert Mod 8TB
How are you calling ImgLoad()?

Another option is to use imgObj.onload - again non-standard, but should be supported by *most* browsers.
Nov 27 '07 #6
Plater
7,872 Expert 4TB
Yeah, I have been thinking of using .onload() and .onerror() to determine rather then .complete

But again, I was hoping there was something in the standard for it.

This works in both FF2 and IE6:
Expand|Select|Wrap|Line Numbers
  1. function ImgLoad(myobj,sSrc)
  2. {
  3.    var oImg=new Image;
  4.    oImg.src="http://mydomain.com/images/"+sSrc;
  5.    oImg.onload=function(){myobj.src=oImg.src}
  6.    oImg.onerror=function(){myobj.src="http://mydomain2.com/images/"+sSrc}
  7. }
  8.  
Call the function with the object of your image and the filename.
If it find the first file it changes the src on the object to it.
On error it sets the the src to the 2nd location.
If it doesn't find it on the 2nd location it will just show a broken image like it should
Nov 27 '07 #7
acoder
16,027 Expert Mod 8TB
One other possibility is to use Ajax to check if the image exists.
Nov 27 '07 #8
Plater
7,872 Expert 4TB
One other possibility is to use Ajax to check if the image exists.
I already have an XMLHttpRequest busy doing stuff.
It was enough trouble getting that in there correctly.
Stupid errors always thrown.
Nov 27 '07 #9
acoder
16,027 Expert Mod 8TB
I already have an XMLHttpRequest busy doing stuff.
It was enough trouble getting that in there correctly.
Stupid errors always thrown.
That shouldn't be the case. You could even have simultaneous XMLHttpRequests.

Do you mean JavaScript errors? Perhaps you could post some of your code.
Nov 28 '07 #10
Plater
7,872 Expert 4TB
Haha ok you asked for it then.

Here's an example of the state change handler function I use for one of the requests:
Expand|Select|Wrap|Line Numbers
  1. function handleSaveSmtpSettingsReponse()
  2. {
  3.     if(http.readyState == 4)
  4.     {
  5.         var update = new Array();
  6.         if (http.status=="200")
  7.         {
  8.             var response = http.responseText;    
  9.             if (response!="")
  10.             {
  11.               if(response.indexOf('|' != -1)) 
  12.               {
  13.                     update=response.split('|');
  14.                     if (update.length>0)
  15.                     {
  16.                         if (update[1].indexOf("SUCCESS")>-1)
  17.                         {
  18.                             var line=update[1];
  19.                             alert('Smtp Settings Saved Successfully.');
  20.                             resetSaveSMTP();
  21.                         }//end of found "SUCCESS"
  22.                         else
  23.                         {
  24.                             ShowError('Smtp Settings **NOT** Saved.');
  25.                         }
  26.                     }//end of update split("|") to have multiple sections
  27.               }//end of response.indexof("|")
  28.             }//end of response!=""
  29.         }//end of status==200
  30.         else if(http.status==12029)
  31.         {//only occurs in firefox?
  32.             ShowError('Problem Communicating');
  33.         }
  34.         else
  35.         {
  36.             alert(http.status);
  37.         }            
  38.     }//end of readystate=4
  39. }//end of function
  40.  
I really should also have try/catch blocks there since firefox's javascript throws errors when I navigate to a new page before the request has come back (it comes back and goes "these functions don't exist")
Nov 28 '07 #11
acoder
16,027 Expert Mod 8TB
I really should also have try/catch blocks there since firefox's javascript throws errors when I navigate to a new page before the request has come back (it comes back and goes "these functions don't exist")
Is that the only time that errors occur? What is the exact error message?
Nov 28 '07 #12
Plater
7,872 Expert 4TB
That was the culmination of me trying to track every situation possible.
I think the errors might not exist, but are caused by firebug trying to track things.

Regardless, using the .onload()/.onerror() seems to be working.
Nov 28 '07 #13
acoder
16,027 Expert Mod 8TB
Regardless, using the .onload()/.onerror() seems to be working.
At least you've got it working with your original solution.

I still think you could give the Ajax route a shot, but it's up to you!
Nov 29 '07 #14
Plater
7,872 Expert 4TB
I had a goof in my post on the "working solution", sometimes it wasn't, and I found out why.

Expand|Select|Wrap|Line Numbers
  1. function ImgLoad(myobj,sSrc)
  2. {
  3.    var oImg=new Image;
  4.    oImg.onload=function(){myobj.src=oImg.src}
  5.    oImg.onerror=function(){myobj.src="http://www.mydomain1.com/images/"+sSrc}
  6.    oImg.src="http://www.mydomain.com/images/"+sSrc;            
  7. }
  8.  
Need to assign the handlers prior to setting the SRC.
Sometimes it would do the SRC so fast (image is cached locally?) that it would complete before assigning event handlers.
Nov 29 '07 #15
acoder
16,027 Expert Mod 8TB
Need to assign the handlers prior to setting the SRC.
Sometimes it would do the SRC so fast (image is cached locally?) that it would complete before assigning event handlers.
That would probably be the case. To avoid caching, you can add a random parameter or the date/time to get a unique request.
Nov 30 '07 #16

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

2 posts views Thread by Roger Withnell | last post: by
3 posts views Thread by Dennis Allen | last post: by
2 posts views Thread by CDWaddell | last post: by
6 posts views Thread by darthmincho | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by suresh191 | last post: by
reply views Thread by harlem98 | last post: by
reply views Thread by harlem98 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.