Detect when images added to DOM have been loaded

前端 未结 2 1300
执笔经年
执笔经年 2021-01-26 03:04

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,

2条回答
  •  鱼传尺愫
    2021-01-26 03:31

    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 '';
    }).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;
    }
    
    
    

提交回复
热议问题