简体   繁体   中英

Javascript function to fire after images have finished loading (no jQuery)

I have the following code (the relevant parts):

window.addEventListener("load", loadImages, false);

var imgl = new Array();

function loadImages() {
    var img = [
        "img1",
        "img2",
        "img3",
        "etc"
    ];
    imgl[img.length-1].onload = function () {
        alert();
        initialise();
    }
    for (i = 0; i < img.length; i++) {
        imgl[img[i]] = new Image();
        imgl[img[i]].src = "img/"+img[i]+".png";
    }
}

function initialise() {
    //...
}

and I want to fire the initialise() function after all the images have finished loading, but nothing I tried worked. (Btw the alert() in the example is for testing, and I'm not getting it.) Why is this wrong? Other methods of doing this are also appreciated.

also I don't want to use jQuery, only if absolutely unavoidable.

Thanks in advance.

EDIT:

The following doesn't work either, although making more sense:

for (i = 0; i < img.length; i++) {
        imgl[img[i]] = new Image();
    }
    imgl[imgl.length-1].onload = function () {
        initialise();
    }
    for (i = 0; i < img.length; i++) {
        imgl[img[i]].src = "img/"+img[i]+".png";
    }

imgl[img.length-1] doesn't exist, therefore cannot have an "onload" property.

You initialize img1 at the beginning, but never populate it.

In other words: img.length-1 = 3

img1[3] doesn't exist.

I'm getting the following error message:

Uncaught TypeError: Cannot set property 'onload' of undefined

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