Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: $.get(url) breaks my sequential script execution

My attention is to check a calculated Image URI, if it exists…

If i do this for images, that are shown as overlays:

$.get(first_url).done(function(){
  $('#any_DOM_id').append('<img id="first_image" src="'+first_url+'"/>');
}).fail(function(){
  $('#any_DOM_id').append('<img id="first_image" src="'+fallback_url+'"/>');
});

/*** HERE is something big happening and is calculated ***/
.
. 
.
. 
.
$.get(second_url).done(function(){
  $('#any_DOM_id').append('<img id="second_image" src="'+second_url+'"/>');
}).fail(function(){
  $('#any_DOM_id').append('<img id="second_image" src="'+fallback_url+'"/>');
});
.
. 
.
$.get(third_url).done(function(){
  $('#any_DOM_id').append('<img id="third_image" src="'+third_url+'"/>');
}).fail(function(){
  $('#any_DOM_id').append('<img id="third_image" src="'+fallback_url+'"/>');
});
.
. 
.
$('#any_DOM_id').append('<img id="fourth_image" src="'+fourth_url+'"/>');

my sequential Chronology is broken, so the images are not in the right position at the layers. Have I to use $.get on all images, or does $.get kills the Chronology always?

EDIT:

This is what i'am doing: enter image description here

the images have to be in order like this:

<style>
  .image_wrapper{
    position:relative;
  }
  .image_wrapper img{
    position:absolute;
  }     
</style>
<div id="image_wrapper">
  <img id="first_image" src="first_url"/>
  <img id="second_image" src="second_url"/>
  <img id="third_image" src="third_url"/>
  <img id="fourth_image" src="fourth_url"/>
</div>
like image 258
Viktor Avatar asked Mar 22 '26 05:03

Viktor


1 Answers

Using .reduce() like a boss

[first_url, second_url, third_url, fourth_url].reduce(function(promise, url) {
    return promise.then(function() {
        return $.get(url);
    }).then(function(urlContents) {
        $('#any_DOM_id').append('<img id="my_image" src="'+url+'"/>');
    }).then(null, function() {
        $('#any_DOM_id').append('<img id="my_image" src="'+fallback_url+'"/>');
        return $().promise();
    });
}, $().promise());
like image 97
Esailija Avatar answered Mar 24 '26 17:03

Esailija