Detect when images added to DOM have been loaded

前端 未结 2 1301
执笔经年
执笔经年 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 '<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>

    0 讨论(0)
  • 2021-01-26 03:51

    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.

    0 讨论(0)
提交回复
热议问题