I am having a bit of an issue with image loading in JavaScript. I want a series of images to load sequentially i.e. image 2 only starts loading when image 1 has completely finished loading.
The problem I am finding is that the JavaScript onLoad method does not fire when the image has completed loading, but when the image starts loading. Therefore the smallest image is always going to be the first to load regardless of where in the queue it is. I have put together a simple example of what i mean in JS fiddle (HTML and JS code is below as well).
Any ideas how I can wait until the image has completely loaded before starting to load the next one – it can’t be that hard surely?
Note : I originally wrote it using the jQuery .load function and got the same result which is why I was messing about in raw JS.
HTML code:
<ul>
<li><img src="" alt="image 1" width="210" height="174"></li>
<li><img src="" alt="image 2" width="210" height="174"></li>
<li><img src="" alt="image 3" width="210" height="174"></li>
<li><img src="" alt="image 4" width="210" height="174"></li>
<li><img src="" alt="image 5" width="210" height="174"></li>
</ul>
<a href="#" id="loader">Load the images</a>
JS code:
var imgArr = [
"http://media.topshop.com/wcsstore/ConsumerDirectStorefrontAssetStore/images/colors/color7/cms/pages/static/static-0000038166/images/zine-HP-UK.jpg",
"http://media.topshop.com/wcsstore/ConsumerDirectStorefrontAssetStore/images/colors/color7/cms/pages/static/static-0000038166/images/Valentine_UK.jpg",
"http://media.topshop.com/wcsstore/ConsumerDirectStorefrontAssetStore/images/colors/color7/cms/pages/static/static-0000038166/images/crop_UK__.jpg",
"http://media.topshop.com/wcsstore/ConsumerDirectStorefrontAssetStore/images/colors/color7/cms/pages/static/static-0000038166/images/hitlist_UK--.jpg",
"http://media.topshop.com/wcsstore/ConsumerDirectStorefrontAssetStore/images/colors/color7/cms/pages/static/static-0000038166/images/chinese_new_year_UK_new_0402.jpg"
],
totalImgs = imgArr.length,
count = 0;
function onLoaded(count) {
console.log("fired onload "+count);
var currentImg = $('li:eq('+count+') img');
currentImg.attr('src', imgArr[count]).css('display','block');
count++;
if (count < totalImgs) {
loadImg(count);
};
}
function loadImg(count) {
imgObj = new Image()
imgObj.src = imgArr[count];
imgObj.onLoad = onLoaded(count);
}
$('#loader').click(function() {
loadImg(count);
});
The problem here is that not the handler function is assigned to the
onloadevent of theImagebut the return value ofonLoaded. You’d need to sayimgObj.onload = onLoaded;For thecurrentImgyou can usethisas the handler will be invoked on theImageobject. For passing other parameters, an alternative way is needed.