Detect when images added to DOM have been loaded

2020-05-06 13:51发布

问题:

Say, user opens a page, clicks on a button, and popup with images appears. How do I detect when all of the images have been loaded? I can't use window.onload here, since the page had already been loaded with all the assets. To make it clear, I want to find out final extents of the popup.

Popup is added to DOM like so:

var popup = document.createElement('div');
popup.innerHTML = '...';
document.body.appendChild(popup);

回答1:

Simply:

var image = document.getElementById('image');

image.onload = function () {
    alert ("The image has loaded!");        
};

setTimeout(function(){
    image.src = "http://lorempixel.com/500/500";         
}, 5000);
<img id="image" src="">

See https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload and Javascript callback for knowing when an image is loaded for more.



回答2:

Based on this answer. Hopefully that is enough.

var cons = document.querySelector('#console');
var popup = document.createElement('div');
popup.className = 'popup';
popup.innerHTML = _.range(10).map(function(i) {
    return '<img src="http://via.placeholder.com/50/50">';
}).join('');
document.body.insertBefore(popup, cons);
waitForImages(popup).then(function() {
    d('loaded');
})

function d(s) {
    var text = document.createTextNode(s);
    cons.appendChild(text);
    var br = document.createElement('br');
    cons.appendChild(br);
}

function waitForImages(el) {
    var images = document.querySelectorAll('img');
    return Promise.all(_.compact(_.map(images, function(img) {
        if (img.complete) {
            d('img.complete');
            return;
        } else
            return new Promise(function(resolve, reject) {
                img.addEventListener('load', function() {
                    d('onload event');
                    resolve();
                });
            });
    })));
}
.popup {
    overflow: hidden;
}
img {
    float: left;
    margin: 0 5px 5px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.5.0/bluebird.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<div id="console">
</div>