473,378 Members | 1,510 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

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 44023
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

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

Similar topics

2
by: Roger Withnell | last post by:
I browse for an image using form input type file and call a JavaScript function with onchange. I then want the function to check the image's properties (width, height, filesize). In WinIE,...
3
by: Dennis Allen | last post by:
Hi. I've been trying to write Javascript code that checking if an image exists. If it doesn't exist, I want to load a known image. I've tried: if (document.images) { var tester=new Image() //...
2
by: CDWaddell | last post by:
I'm trying to write some code to validate if an image is present on the server. If the image is missing then I want to display out noimage.gif file. I have a website that has thousands of...
1
by: James | last post by:
vb.net 2003 i wrote a windows service that does threading. My codes are a) the service thread will read a list of machine from a text file (machines.txt). b) it then logon using the below...
6
by: darthmincho | last post by:
Hi. I want to check if an image exists on a remote server, and if it does, show it. I If it does not exist I want to show a default message. I have previously used these chunks of code but none...
16
by: browntown | last post by:
so I have this application I'm nearly finished with. The only thing the client has requested is the ability to submit the form by pressing "enter". I didn't think this would be a huge pain in the...
3
by: Chandra | last post by:
How do I programmatically (javascript) check if link is valid in html?
2
by: rblampain | last post by:
I am a casual javascript user. I have a form that ask the visitor to select one option from about 250 radio boxes and then enter his or her details (name and address). To avoid the frustration...
2
Manikgisl
by: Manikgisl | last post by:
HI. How to check File exists in Web Share C# try { WebRequest request = HttpWebRequest.Create("http://www.microsoft.com/NonExistantFile.aspx"); request.Method = "HEAD"; // Just get...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.