Line by line execution for javascript object

2.2k views Asked by At

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

There are 1 answers

3
rink.attendant.6 On BEST ANSWER

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.