In a jQuery project, I add several images to the page after the download is complete using the append () function. After all the additions are complete, I need to call a function that determines the width and height of each of these new elements, so I can correctly align them on the page.
This works well on my rather slow development PC. But when testing on a fast machine in a fast browser (for example, in Chrome), it turns out that calling the layout function immediately after the addition is complete leads to random, strange behavior. The problem of performing a layout function with a slight delay solves the problem. I assume that “javascript is adding new elements” is not the same as “the browser has rendered them displayed,” so measuring their size is not yet possible.
So, I need a way to find out when new elements are actually present so that I can reliably determine their width and height. I do not think document.ready () will help in this case, since the elements are added by the function called in document.load ().
This is the code I copied from another stackoverflow (dude named Pointy, thanks, by the way!)
function called_by_document_load() {
var promises = [];
for (var i=0; i<my_pics.length; i++) {
(function(url, promise) {
var img = new Image();
img.onload = function () {
promise.resolve();
};
img.src = url;
}) (my_pics[i]['url'], promises[i] = $.Deferred());
}
$.when.apply($, promises).done(function() {
}
... with the my_pics array containing the URLs of the uploaded images.
Any ideas ?:-)
Thanks in advance,
Snorri
source
share