Here is a function that will create multiple images and call a callback when they are loaded:
function createImages(srcs, fn) { var imgs = [], img; var remaining = srcs.length; for (var i = 0; i < srcs.length; i++) { img = new Image(); imgs.push(img); img.onload = function() { --remaining; if (remaining == 0) { fn(srcs); } }; img.src = srcs[i]; } return(imgs); } var imgs = createImages(['images/img1.png', 'images/img2.png'], myCallback);
PS When working with .onload for images, you must install the .onload handler before setting the .src value, because the onload handler can immediately work when you set the .src value if the image is in the cache. If you did not install the onload handler in the first place, it may never work, because by the time you install the handler, the image is already loaded. This happens in some browsers. Just set .onload to .src if you need the onload event.
source share