jQuery - How to execute script as soon as we know true height (with images) of ajax-loaded element?

不问归期 提交于 2019-12-13 04:10:36

问题


Say I have a page index.html where my scripts are running, and a page content.html which is a very large, rich document full of images and styled text. I'm loading 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 content html is inserted into the container. But what if I want to do something in that callback that needs to know the full height of the container, such as initialize a custom scrollbar? $("#container").height() won't be accurate yet, because all the images have just started loading and they will change the height of the content as more are loaded.

I'm now using https://github.com/desandro/imagesloaded to detect when all the images in the content are done loading and then firing my callback then. However, this slows everything down... my page has a big "loading..." message above the container for the entire time it takes to load every image.

I can tell that the document seems to "know" the height of each image before it's loaded, because just as an image begins loading, the rest of the page moves to give it just the right amount of space. The image is given its own "container" of the correct size, and then the image is gradually loaded into that space. What I want to do, ideally, is capture the event of that image "container" being in place, without having to wait for the image itself to fully load. And I'd like to compound that to being able to detect the full final height of (returning to my example above) #container, as soon as possible after i start loading content into it.

Is what I'm trying to do possible?


回答1:


I assume those images on content.html were put there dynamically. If you have those image server side you could assign height and width attributes to those <img> tags and use them to determine the real size of your container a bit faster. If you don't know the dimensions of those images server side then it won't work. Here some info: Should I specify height and width attributes for my IMGs in HTML?



来源:https://stackoverflow.com/questions/9666806/jquery-how-to-execute-script-as-soon-as-we-know-true-height-with-images-of-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!