How to know if all elements in a DIV have been fully loaded?

前端 未结 2 771
悲哀的现实
悲哀的现实 2020-12-29 00:47

There is a div in which there will be some elements (images, iframe, etc) being loaded via Ajax. After those elements have been fully loaded, I need to execute

2条回答
  •  春和景丽
    2020-12-29 01:18

    For images and iframes you can use load event:

    // get all images and iframes
    var $elems = $('#div').find('img, iframe');
    
    // count them
    var elemsCount = $elems.length;
    
    // the loaded elements flag
    var loadedCount = 0;
    
    // attach the load event to elements
    $elems.on('load', function () {
        // increase the loaded count 
        loadedCount++;
    
        // if loaded count flag is equal to elements count
        if (loadedCount == elemsCount) {
            // do what you want
            alert('elements loaded successfully');
        }
    });
    

    You should execute the above script after appending your elements via Ajax into your #div element.

提交回复
热议问题