Question

I need to pause execution of javascript until after the DOM changes are completed. I am making DOM changes with jquery append and setting some post variables with attributes of the appended image. I've looked at similar questions about this but none seem to be relevant to what I am wanting to do. Here is the code:

var newImage = new Image();
newImage.src = *src is retrieved from previous variable*;
newImage.style.display = "none";
$('body').append(newImage);


var postData = {
    height: $('img:last')[0].height,
    width: $('img:last')[0].width
};

In some cases the append will finish and I will get the correct values for height and width, but most of the time the DOM hasn't finished and I just get 0's for the height and width. How can I make the javascript wait for the DOM to finish its changes? I've tried messing around with jQuery .ready but I can't seem to get it right.

Was it helpful?

Solution

You need to put an onload handler on the newImage object, and then initiate the rest of your code from that handler, e.g.:

var newImage = new Image();
newImage.style.display = "none";
newImage.onload = function(ev) {
     // put the loaded image in the DOM
     $('body').append(this);

     // extract its properties
     var postData = {
        height: this.height,
        width: this.width
     }

     // do stuff with postData here
     // ...
};
newImage.src = *src is retrieved from previous variable*;

OTHER TIPS

In this specific case, it looks like you just want to know when the image is loaded and then execute your javascript at that point. You can do that with the onload event (plain javascript) or .load() (jQuery).

var postData = {};
var newImage = new Image();
newImage.style.display = "none";
newImage.onload = function() {
    postData.height = this.height;
    postData.width = this.width;
    // perhaps call some other function here that uses postData
};
newImage.src = *src is retrieved from previous variable*;
$('body').append(newImage);

The .onload handler must be set before the .src value is set or you may miss the load event in some circumstances.

Instead of using the jQuery ready event which triggers when all the html is available in page but not images loaded, you could run your code inside

  $(window).load(function(){
       /* images now loaded ,run image based code*/
   })

This will take longer to fire so there may be code you can run in ready also for elements/events that are not related to images

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top