Last Updated: February 25, 2016
·
2.361K
· blitline-dev

Poll S3 for image using JQuery

If you are processing images and waiting for an image to appear on S3 you can use the following javascript trick(hack) to wait for the image to actually appear there.

INFO: It's not a well-known fact that items that are pushed to S3 are not always available right away. There is a latency between when you "put" and item to an S3 bucket, and when you can publicly "access" that image (like in a browser). Most of the time it's milliseconds, but sometimes it's longer. (Trust us, we know)

Regardless of whether you are waiting for your own image to appear or waiting for a Blitline job to complete and don't have the capacity to use Blitline "postbacks", you can use the following to wait for an image:

function waitForImage(img_id, src, callback) {
    var imageSelector = "#" + img_id;
    var tries = 10;

    $("body").find(imageSelector).remove();

    setTimeout( function() {
        $("body").append("<img style='display:none;' id='"+ img_id +"'/>");
        var $img = $(imageSelector);
        $img.error(function() {
          setTimeout(function() {
            tries -= 1;
            if (tries < 1) {
                callback(false);
            }
            waitForImage(img_id, src, callback);
          }, 5000);
        });
        $img.load(function() {
            callback(true, src);
        });
        $img.attr("src", src + "?"+Math.random().toString());
    }, 1000);
}

So, if you know the location of the photo, you can just call the following from your javascript:

waitForImage("SomeUniqueID", "LocationOfPhotoOnS3",
    function(success, src) {
        if(success) {
            alert("My photo exists at " + src);
        }else{
            alert("10 tries, no photo");
        }
     }
  );

If it's not obvious, "SomeUniqueID" is just an ID that wont conflict with an existing DOM Element, and "LocationOfPhotoOnS3" is the location of the photo you are looking for on S3.