Image Promise

by gradbot

JavaScript

// Attach a done and fail handler for the asyncEvents
function imageLoaded(url){
    var dfd = new jQuery.Deferred();
    
    var img = new Image();
    
    img.onload = function() {
        dfd.resolve("hurray");
    };
        
    img.onerror = function() {
        dfd.reject("sorry");
    };
        
    img.src = url;

    return dfd.promise();
}

$.when(imageLoaded("http://localhost/logo.png")).then(
    function(status){
        alert( status+', things are going well' );
    },
    function(status){
        alert( status+', you fail this time' );
    }
);