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.

1
  • 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. Commented Jun 11, 2015 at 15:14

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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??
@AakashJain I've updated the code and added a working example
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.