JQuery - How to execute a script as soon as we find out the true height (with images) of the element loaded by ajax?

Say I have an index.html page where my scripts work, and a content.html page, which is a very large, rich document with images and stylized text. I load the contents of content.html into <div id="container"></div> on my index.html with:

 $.get("content.html", function(data, textStatus, jqXHR) { $("#container").html(data); contentLoadedCallback(); }); 

In the above example, contentLoadedCallback() is called as soon as the html content is inserted into the container. But what if I want to do something in this callback that needs to know the entire height of the container, for example, initialize a custom scrollbar? $("#container").height() is not yet accurate, because all the images have just started to load, and they will change the height of the content as more are loaded.

Now I use https://github.com/desandro/imagesloaded to determine when all the images in the content are loaded, and then activate my callback. However, this slows things down ... my page has a large "loading ..." message above the container for the entire time it takes to load each image.

I can say that the document seems to β€œknow” the height of each image before loading it, because as soon as the image starts loading, the rest of the page moves to give it just the necessary space. The image gets its own β€œcontainer” of the correct size, and then the image is gradually loaded into this space. Ideally, I want to make it so that the event "container" of this image is recorded, without waiting until the image is fully loaded. And I would like to combine this in order to detect the full final height (returning to my example above) #container as soon as possible after I started loading the content into it.

Am I trying to do this?

0
source share
1 answer

I assume that these images on content.html were placed there dynamically. If you have this side of the image server, you can assign the height and width attributes to these <img> tags and use them to determine the actual size of your container a little faster. If you do not know the sizes of these sides of the image server, this will not work. Here is some information: Should I specify height and width attributes for IMG in HTML?

+2
source

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


All Articles