2

I am trying to validate an image URL if it exists or not using JavaScript. Basically I want to assign the URL to image if its valid. But the JavaScript function which validates the URL, as not executing line-by-line, disrupts the logic and returns all URLs to be true. Is there any way I can hold the control inside the urlExists function till all its threads are completed?

Currently the control do not wait for the result of error message and jumps over it to back to the calling function with true value always. Any idea how can I make the function hold control here?

function urlExists(testUrl) {
    var ret = true;
    var newImage = new Image();
    newImage.src = testUrl;
    $(newImage).error(
        function(){
            ret = false;
        }
    );
    return ret;
}
function changeImagePath(obj){
    var oldUrl = obj.src;
    var newUrl = oldUrl.replace("abc","xyz");
    if(urlExists(newUrl)){
        obj.src = newUrl;
    }   
}

<img src="http://sample.com/images/srpr/logo_abc.png" onclick="changeImagePath(this)" />

Also meant to mention I am dealing with cross-domain image URLs.

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
Aakash Jain
  • 730
  • 1
  • 12
  • 31
  • Image loading is asynchronous, otherwise, the HTTP request would block the main thread and the site could become unresponsive for multiple seconds. You need to use a callback instead of a return value. You can find thousands of examples on StackOverflow. – Tobias Jun 11 '15 at 15:14

1 Answers1

2

You can pass the code in as a callback function to modify the existing image. There is no need to create a new image to perform the check:

function urlExists(img, newUrl, callback) {
  $(img).error(callback).attr('src', newUrl);
}

function changeImagePath(obj) {
  var oldUrl = obj.src;
  var newUrl = oldUrl.replace("200", "x");
  urlExists(obj, newUrl, function() {
    obj.src = oldUrl;
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
Click to attempt to change the image
<img src='https://placekitten.com/g/200/300' alt='cat' onclick='changeImagePath(this);'>

As you can see in your browser's console, an HTTP request is done and a 404 not found is returned. To try a case where it is successful, change "x" in the above example to a number such as 250.

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
  • but the url is anyways assigning to the image, no matter if i change the url back in error callback function in case of a invalid image url?? – Aakash Jain Jun 11 '15 at 17:32
  • @AakashJain I've updated the code and added a working example – rink.attendant.6 Jun 11 '15 at 17:42
  • A query related to the above answer, if the initial image is not valid too, then the function goes into infinite loop into the callback. How can we break it from the loop then? – Aakash Jain Jul 17 '15 at 11:55