JQ gets the correct way to share dynamically loaded image sizes

  • 2020-03-26 23:47:14
  • OfStack

There are some error-prone methods to obtain the size of dynamically loaded images. The main reason for the error is:
You call the code before the image is downloaded from the web page, which is not easy to find in native development.
JQuery load() event handling BUG that gets the wrong size when the image is retrieved from the browser cache.
The error code is:
(error) call the code to get the size immediately after HTML is added


  var html = '';
  $('#my_div').html(html);
  var width = $('#my_div img').width(); // may return 0 

(error) handled with jQuery's load() event


  var html = '';
  var img = $(html);
  html.load(function(){
  // return 0 if image is loaded from browser cache
  var width = img.width();
  });
  $('#my_div').html(img); 

The correct way to do this is to use the JavaScript Image class:
The right way


  var html = '';
  $('#my_div').html(html);
  var ni = new Image();
  ni.onload = function(){
  var width = ni.width;
  }
  ni.src = img.attr(URL); 


Related articles: