JQuery.html (something) detects when injection is complete

In a nutshell, I want the callback to start after the html has been added and the contents of that html is displayed. The reason is that I need to immediately know the height of the new content. Something like that:

$('div').html(tonsofstuff); console.log( $('div').height() ); //works in Firefox, but returns 0 in Chrome setTimeout(function(){ console.log( $('div').height() ); //works everywhere, but takes too long },3000); 

The problem occurs in some browsers (and always in chrome) $ ('div'). height () is triggered before the new content has a height.

My fantasy:

  $('div').html(tonsofstuff, function(){ console.log( $('div').height() ); }); or even $('div').html(tonsofstuff).load(function(){ console.log( $('div').height() ); }); 
+6
source share
3 answers

This is what I do:

 var height = $('div').html(tonsofstuff).height(); 

I had no problem waiting for it to render.

+5
source

If the problem occurs in chrome, I assume that the content you paste contains images. Chrome does not calculate image sizes until they are fully loaded (DOM ready is not enough). So what you can usually fix is ​​doing your rendering in the window.onload event. Thus, make sure that the downloaded images and .height() / .width() will work fine. Although I understand that this is not always possible, because the window.onload event fires more after this DOMContentLoaded .

Another approach is to explicitly specify image values ​​through the width and height attributes of the corresponding image tag. This may work if you know the size of the images. In this case, there is no need to execute your logic on window.onload .

0
source

If your tonsofstuff has images, the setTimeout attack is the wrong approach. You need to know when all images are loaded, and then perform DOM height calculations. And for this you may have to mask html to download, search for images and use somethig call like Image Preloader Plugin , I do not recommend this; it is pretty trivial to write your own (although there may be some gotchas with specific methods). I just know that there are things that should work very well.

0
source

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


All Articles