-3

Using Javascript I can replace image by changing src parameter, such as

document.getElementById('image-id').src = 'new-image.png';

If I need change image dynamically when and only the new image is available and valid, how I need to adjust the above code to perform replacement only if browser is able to get the image?

Other words, if HTTP request for new-image.png ends with error (403, 404, 500, ...), or if the file is not a valid image, I want to keep the original image and do not execute the code, because otherwise browser shows no image.

Ωmega
  • 42,614
  • 34
  • 134
  • 203
  • 1
    Maybe you can start here : http://stackoverflow.com/a/4236041/3315914 – rpax May 05 '14 at 12:06
  • 3
    This appears to be what you need: http://stackoverflow.com/questions/1977871/check-if-an-image-is-loaded-no-errors-in-javascript – ajm May 05 '14 at 12:07
  • @rpax - Existence of file does not necessary mean that the file is a valid image! – Ωmega May 05 '14 at 12:25

6 Answers6

3

You can load the image separately and swap it in if successful:

var img = document.createElement('img');
img.onload = function() {
    // It worked, either replace `image-id` with this new `img` element:
    var oldImg = document.getElementById("image-id");
    oldImg.parentNode.insertBefore(img, oldImg);
    oldImg.parentNode.removeChild(oldImg);
    img.id = "image-id";

    // ===OR===

    // Just set `image-id`'s `src` (it'll come from cache, presumably)
    document.getElementById("image-id").src = img.src;
    img = img.onload = null;
};
img.src = "new-image.png"; // Important to do this AFTER hooking `onload` above
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

as said in: How do I check if file exists in jQuery or JavaScript?

perform a ajax reguest on that file (this one done with jquery)

$.ajax({
    url: 'http://www.example.com/somefile.ext',
    type: 'HEAD',
    error: function()
    {
        // file does not exist
    },
    success: function()
    {
        // file exists
    }
});
Community
  • 1
  • 1
J0N3X
  • 228
  • 2
  • 14
0

Try this:

Using Javascript:

function imageExists(image_url){
 var http = new XMLHttpRequest();
 http.open('HEAD', image_url, false);
 http.send();
 return http.status != 404;
}
if(imageExists('new-image.png'))//when image exists
   document.getElementById('image-id').src = 'new-image.png';

Using Jquery:

var image_url='new-image.png';
$.get(image_url)
.done(function() { 
  document.getElementById('image-id').src = 'new-image.png';

}).fail(function() { 
    // Image doesn't exist

})

Reference

Community
  • 1
  • 1
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
  • 1
    For image, you don't really need to make any ajax request, onload event will be fired only on success – A. Wolff May 05 '14 at 12:11
  • however if you use ajax you can find whether image exists or not without actually loading the image. Consider a 10 mb image file, you don't want to load it just to find if it exists or not. It depends on the use case, if your aim is to load the image anyways (like this question) then onload is better. – Abhas Tandon May 05 '14 at 12:15
0
 // The "callback" argument is called with either true or false
 // depending on whether the image at "url" exists or not.
 function imageExists(url, callback) {
  var img = new Image();
  img.onload = function() { callback(true); };
  img.onerror = function() { callback(false); };
 img.src = url;
}

// Sample usage
var imageUrl = 'http://www.google.com/images/srpr/nav_logo14.png';
imageExists(imageUrl, function(exists) {
 console.log('RESULT: url=' + imageUrl + ', exists=' + exists);
});
Gaurang s
  • 831
  • 6
  • 18
0

Using jQuery, you could use:

function checkImage(img, src) {
    $("<img/>").one('load', function () {
        img.src = src;
    }).attr('src',src);
}

Use it like this:

checkImage(document.getElementById('image-id'), 'new-image.png');
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
0

Common solution:

$("<img/>")
  .load(function() {
    document.getElementById('image-id').src = 'new-image.png';
  })
 .attr('src', 'new-image.png');

Clean solution:

$("<img/>")
  .load(function() {
    document.getElementById('image-id').src = 'new-image.png';
    $(this).remove();
  })
  .error(function() {
    $(this).remove();
  })
  .attr('src', 'new-image.png');

Ωmega
  • 42,614
  • 34
  • 134
  • 203