How do you know if the pictures were downloaded in the block?



  • There's a block that contains pictures. After loading all the pictures in the block, you have to perform the function. How do you know all the pictures in the block are downloaded?



  • We can sign for an event. onload All pictures, raise the counter after loading each picture, and give a function when it's loaded.

    var block = document.getElementById("block");
    bindImagesOnload(block, function() {
        console.log("Все картинки загружены!");
    });
    function bindImagesOnload(node, fn) {
        var imgs = node.getElementsByTagName("img"),
            length = imgs.length;
        var counter = 0;
        var onload = function() {
            counter++;
            if (counter >= length)
                fn();
        };
        for (var i = 0; i < length; i++) {
            imgs[i].onload = onload;
        }
    }
    <div id="block">
        <img src="//www.google.com/logos/doodles/2015/thanksgiving-2015-6462359094689792-hp.jpg">
        <img src="//www.google.ru/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
        <img src="//www.google.cn/landing/cnexp/google-search.png">
    </div>




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2