Javascript - execute after all images have loaded

前端 未结 9 1345
陌清茗
陌清茗 2020-12-01 05:53

Having read other people\'s questions I thought

window.onload=...

would answer my question. I have tried this but it executes the code the

9条回答
  •  再見小時候
    2020-12-01 06:05

    Here is a quick hack for modern browsers:

    var imgs = document.images,
        len = imgs.length,
        counter = 0;
    
    [].forEach.call( imgs, function( img ) {
        if(img.complete)
          incrementCounter();
        else
          img.addEventListener( 'load', incrementCounter, false );
    } );
    
    function incrementCounter() {
        counter++;
        if ( counter === len ) {
            console.log( 'All images loaded!' );
        }
    }
    

    Once all the images are loaded, your console will show "All images loaded!".

    What this code does:

    • Load all the images in a variable from the document
    • Loop through these images
    • Add a listener for the "load" event on each of these images to run the incrementCounter function
    • The incrementCounter will increment the counter
    • If the counter has reached the length of images, that means they're all loaded

    Having this code in a cross-browser way wouldn't be so hard, it's just cleaner like this.

提交回复
热议问题