JQuery: detect if browser rendered after adding ()

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() {
    // add the new images using append()
    // when done, call my own layout function
  }

... with the my_pics array containing the URLs of the uploaded images.

Any ideas ?:-)

Thanks in advance,

Snorri

+4
source share
1 answer

After adding new images using append, output the control to the browser so that the browser can update ui and then call the layout function. You can make me use setTimeout with a delay set to 0.

$.when.apply($, promises).done(function() {
    // add the new images using append()

    setTimeout(function () {
        // when done, call my own layout function  
    }, 0);
}

There are many SO threads that explain why this works and is useful.

Here is one good explanation.

In addition, you should watch the video of Philip Roberts in the browser events loop.

+1
source

Source: https://habr.com/ru/post/1625477/


All Articles