سؤال

I am dynamically loading content in a page using jQuery Ajax. The content contains images, so I need to know at what point all the images will be loaded, something like DOM Ready.

Initially content will be hidden. After the images were loaded successfully I display the div containing them. Is there a method to detect when the loaded content with Ajax is ready to display? Ajax success function is called when the text response is returned from server but I need to execute a function when is all loaded and images are loaded as well.

هل كانت مفيدة؟

المحلول

If you have just inserted a bunch of HTML into your document (containing some <img> tags) and you want to know when all those new images are loaded, you can do it like this. Let's suppose that the dynamic content was all inserted into the #root object. Right after you've inserted the dynamic contend, you can run this code:

function notifyWhenImagesLoaded(rootSelector, callback) {
    var imageList = $(rootSelector + " img");
    var imagesRemaining = imageList.length;

    function checkDone() {
        if (imagesRemaining === 0) {
            callback()
        }
    }

    imageList.each(function() {
        // if the image is already loaded, just count it
        if (this.complete) {
            --imagesRemaining;
        } else {
            // not loaded yet, add an event handler so we get notified
            // when it finishes loading
            $(this).load(function() {
                --imagesRemaining;
                checkDone();
            });
        }
    });
    checkDone();
}

notifyWhenImagesLoaded("#root", function() {
    // put your code here to run when all the images are loaded
});

You call this function after you've inserted the dynamic content. It finds all images tags in the dynamic content and checks if any have already loaded. If they have, it counts them. If they haven't, then it installs a load event handler so it will get notified when the image loads. When the last image finishes loading, it calls the callback.

نصائح أخرى

ajax

$.ajax({
    type: "POST",
    url: "myfile.*",
    data: {data : params}, 
    cache: false,
    success: function(return_data){
       //here you have the answer to Ajax
       //at this point you have the content ready for use
       //in your case here you would find the images that you got back from the file called by ajax
    }
});

you can use the on method with load. Count how many items you have in total and use the load event to have a number of total images loaded. You can even build a progress bar like this.

Something like that and after you have finished with the ajax call

$('img').on('load', function(){

  // Count items here      

});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top