0

I have two request, one is load image(the back-end server will cost much time), the other is ajax. I want like following:

$.when(
   [do image load]
   [do ajax]
).then(
  alert('all complete')
)

However, $.when and then use for multiple ajax request, how to deal with the ajax and image loading

sknight
  • 1,063
  • 11
  • 15
  • 1
    *"However, $.when and then use for multiple ajax request"* - They're not *exclusively* for Ajax requests, they're for promises (or jQuery's deferreds). You can create your own promise that is resolved when the image loads and pass that promise to `$.when()`. – nnnnnn May 31 '17 at 04:07

2 Answers2

0
$.when(
  $.get("/ajax/", function(response) {
    //process ajax
  }),
  $.get("/assets/image.png", function(image) {
    // process image
  }),
).then(function() {
  // All is ready now, so...
  alert('all complete')
});
Hongbin Wang
  • 1,186
  • 2
  • 14
  • 34
0

I would like to suggest Gauri's imgLoad plugin from jQuery callback on image load (even when the image is cached)

 /**
 * Trigger a callback when 'this' image is loaded:
 * @param {Function} callback
 */
(function($){
    $.fn.imgLoad = function(callback) {
        return this.each(function() {
            if (callback) {
                if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
                    callback.apply(this);
                }
                else {
                    $(this).on('load', function(){
                        callback.apply(this);
                    });
                }
            }
        });
    };
})(jQuery);

Usage,

$('#img-if').imgLoad(function(){
    // inside the image complete callback
    $.ajax({
        ....
        success:function(response){
           // final code to be executed here
        }
    })
});
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106