简体   繁体   中英

I want to preload an array of images in javascript and pause until they are all loaded

I have a code that depends on an array of large images being loaded first, so I'm trying to do something like this:

var loading = 0;
    var i = 0;
    var imgs = [];
    var background = [
        'bg1-1', 'bg1-2', 'bg1-3', 'bg1-4',
        'bg2-1', 'bg2-2', 'bg2-3', 'bg2-4',
        'bg3-1', 'bg3-2', 'bg3-3', 'bg3-4',
        'bg4-1', 'bg4-2', 'bg4-3', 'bg4-4'
    ];

    for (i = 0; i < background.length; i++) {
        imgs[i] = document.getElementById(background[i]);
        imgs[i].onload = function() {
            loading++;
        }
    }

    while (loading < 16) {  }

    alert('images loaded!'); //I need to ensure images are fully loaded here.

So, it just hangs and never pulls out of the while loop.

Put the condition and the alert in the callback.

var loading = 0;

for (i = 0; i < background.length; i++) {
    imgs[i] = document.getElementById(background[i]);
    imgs[i].onload = function() {
        loading++;
        if (loading >= background.length)
            alert("all done");
    }
}

And really it would be better to reuse that function.

var loading = 0;

function imgHandler() {
    loading++;
    if (loading >= background.length)
        alert("all done");
}

for (i = 0; i < background.length; i++) {
    imgs[i] = document.getElementById(background[i]);
    imgs[i].onload = imgHandler;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM