Search code examples
jqueryimageurlfile-exists

jQuery: insert image only if it exists


I'm using jQuery to insert an image and blob of text into my document, but I only want to include the image if it actually exists (the image path is a variable, img_url, that may or may not reference an existing image).

Here's a simplified version of my code:

var text = data.html,
    image = '<img class="myimage" src="' + img_url + '" />';

var imageTest = $("<img>");
    imageTest.attr('src', img_url).load(function() {
        alert("image exists");
    }).error(function() {
        alert("image doesn't exist");
        imageTest.remove();
    });

if (imageTest.length) {
    $("#content").html(image + text);   
} else {
    $("#content").html(text);
}

While I do get the correct alert based on whether or not the image exists, imageTest.length always evaluates to 1, so I still end up with the image always being inserted into #content, even if it's broken.

Where am I going wrong? imageTest.remove() should delete the image element if it fails to load, so therefore its length should be 0, no?


Solution

  • You can do this

    var imageTest = $("<img>");
    imageTest.attr('src', img_url).load(function() {
         alert("image exists");
         $("#content").html(image + text); // <-- move it here - if loaded successfully add it
    }).error(function() {
         alert("image doesn't exist");
         imageTest.remove(); // <-- don't need this since it's not even in the dom
         $("#content").html(text); // <-- move it here - if failed then just add text
    });
    

    Though I noticed you will probably get [Object object].. You can use append instead or you will have to convert the object into a String

    var text = "test text";
    var imageTest = $("<img>");
    imageTest.attr('src', 'http://dummyimage.com/300').load(function () {
      alert("image exists");
      $("#content").empty().append(imageTest).append(text); // <-- move it here - if loaded successfully add it
    }).error(function () {
      alert("image doesn't exist");
      imageTest.remove(); // <-- don't need this since it's not even in the dom
      $("#content").html(text); // <-- move it here - if failed then just add text
    });
    

    FIDDLE

    Or as converting it into a string

    var text = "test text";
    var imageTest = $("<img>");
    imageTest.attr('src', 'http://dummyimage.com/300').load(function () {
      alert("image exists");
      var img = $('<div/>').append(imageTest.clone()).html(); // get it as a String
      $("#content").html(img + text); // <-- move it here - if loaded successfully add it
    }).error(function () {
      alert("image doesn't exist");
      imageTest.remove(); // <-- don't need this since it's not even in the dom
      $("#content").html(text); // <-- move it here - if failed then just add text
    });
    

    FIDDLE