How can I know when ajax loaded content finish the

2019-04-15 23:49发布

问题:

I'm loading html from an ajax request, and some img tags in it.

I need to know when the images loaded in the ajax are fully loaded to resize the container. I don't know how many images are in the result, so I can't simply check the .complete value.

Do you know a solution for this?

Thank you!

Leandro

回答1:

If you're using jQuery, the $(window).load() command can set up a function to be called once all the images are loaded, as follows:

$(window).load(
    function() {
        // weave your magic here.
    }
);

If you're not using jQuery, I'd just do what I've done when I want a little bit of its functionality: download it and examine the source to see how it does it. Then do that :-)



回答2:

XMLHTTPrequests have properties that you can use to determine when the load has completed. If you are using javascript directly, you would need to assign a function to the onreadystatechange event. This is called each time that the state changes. The states are stored in ReadyState and are: 0 Uninitiated 1 Loading 2 Loaded 3 Interactive 4 Complete

In your function you check that the status is 4 and call the other required functions

JQuery has events that tell you when certain things have occurred. View the AJAX Documentation



回答3:

Ok, thanks to Pax, I've found the solution.

On the success event of the ajax request (using jQuery), I've added the following code:


$('img', this).load(function() {
    resize_element(this);
});

Thanks both of you!