javascript: check if image src exists

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    javascript: check if image src exists

    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:



    I would like to attempt to load pictures from:

    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:
    [code=html]
    <img src="http://mydomain.com/images/image1.jpg" onerror="this.s rc='http://mydomain2.com/images/image1.jpg'" />
    [/code]
    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?
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    Try using the complete property. You could use setInterval/setTimeout to make a check that the image has loaded after a period of time.

    Comment

    • Plater
      Recognized Expert Expert
      • Apr 2007
      • 7872

      #3
      Originally posted by acoder
      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:
      [code=javascript]
      function ImgLoad(sSrc)
      {
      var oImg=new Image;
      oImg.src="http://mydomain.com/images/"+sSrc;
      if(oImg.complet ed)
      {
      return oImg.src;
      }
      else
      {
      return "http://mydomain2.com/images/"+sSrc;
      }
      }
      [/code]
      However, it seems that the .src call doesn't block so it will always show "completed" as false?

      Comment

      • acoder
        Recognized Expert MVP
        • Nov 2006
        • 16032

        #4
        No, the property is called "complete" and you use it on the Image object, not on its source.

        Comment

        • Plater
          Recognized Expert Expert
          • Apr 2007
          • 7872

          #5
          Originally posted by acoder
          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....

          Comment

          • acoder
            Recognized Expert MVP
            • Nov 2006
            • 16032

            #6
            How are you calling ImgLoad()?

            Another option is to use imgObj.onload - again non-standard, but should be supported by *most* browsers.

            Comment

            • Plater
              Recognized Expert Expert
              • Apr 2007
              • 7872

              #7
              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:
              [code=javascript]
              function ImgLoad(myobj,s Src)
              {
              var oImg=new Image;
              oImg.src="http://mydomain.com/images/"+sSrc;
              oImg.onload=fun ction(){myobj.s rc=oImg.src}
              oImg.onerror=fu nction(){myobj. src="http://mydomain2.com/images/"+sSrc}
              }
              [/code]
              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

              Comment

              • acoder
                Recognized Expert MVP
                • Nov 2006
                • 16032

                #8
                One other possibility is to use Ajax to check if the image exists.

                Comment

                • Plater
                  Recognized Expert Expert
                  • Apr 2007
                  • 7872

                  #9
                  Originally posted by acoder
                  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.

                  Comment

                  • acoder
                    Recognized Expert MVP
                    • Nov 2006
                    • 16032

                    #10
                    Originally posted by Plater
                    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.

                    Comment

                    • Plater
                      Recognized Expert Expert
                      • Apr 2007
                      • 7872

                      #11
                      Haha ok you asked for it then.

                      Here's an example of the state change handler function I use for one of the requests:
                      [code=javascript]
                      function handleSaveSmtpS ettingsReponse( )
                      {
                      if(http.readySt ate == 4)
                      {
                      var update = new Array();
                      if (http.status==" 200")
                      {
                      var response = http.responseTe xt;
                      if (response!="")
                      {
                      if(response.ind exOf('|' != -1))
                      {
                      update=response .split('|');
                      if (update.length> 0)
                      {
                      if (update[1].indexOf("SUCCE SS")>-1)
                      {
                      var line=update[1];
                      alert('Smtp Settings Saved Successfully.') ;
                      resetSaveSMTP() ;
                      }//end of found "SUCCESS"
                      else
                      {
                      ShowError('Smtp Settings **NOT** Saved.');
                      }
                      }//end of update split("|") to have multiple sections
                      }//end of response.indexo f("|")
                      }//end of response!=""
                      }//end of status==200
                      else if(http.status= =12029)
                      {//only occurs in firefox?
                      ShowError('Prob lem Communicating') ;
                      }
                      else
                      {
                      alert(http.stat us);
                      }
                      }//end of readystate=4
                      }//end of function
                      [/code]

                      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")

                      Comment

                      • acoder
                        Recognized Expert MVP
                        • Nov 2006
                        • 16032

                        #12
                        Originally posted by Plater
                        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?

                        Comment

                        • Plater
                          Recognized Expert Expert
                          • Apr 2007
                          • 7872

                          #13
                          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.

                          Comment

                          • acoder
                            Recognized Expert MVP
                            • Nov 2006
                            • 16032

                            #14
                            Originally posted by Plater
                            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!

                            Comment

                            • Plater
                              Recognized Expert Expert
                              • Apr 2007
                              • 7872

                              #15
                              I had a goof in my post on the "working solution", sometimes it wasn't, and I found out why.

                              [code=javascript]
                              function ImgLoad(myobj,s Src)
                              {
                              var oImg=new Image;
                              oImg.onload=fun ction(){myobj.s rc=oImg.src}
                              oImg.onerror=fu nction(){myobj. src="http://www.mydomain1.c om/images/"+sSrc}
                              oImg.src="http://www.mydomain.co m/images/"+sSrc;
                              }
                              [/code]

                              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.

                              Comment

                              Working...