Reputation: 5383
I Have 2 heavy images on my landing page as background. They are going to be displayed in a given order so I am trying to load them in that order for a better user experience. I tried the code below :
function loadImages(){
img1= new Image();
img2= new Image();
img1.onLoad=img1Loaded();
img1.src='img/bg1.jpg';
}
function img1Loaded(){
console.log('image1 loaded');
window.document.getElementById('page1').style.background= " #009ee3 url(img/bg1.jpg) no-repeat left top";
window.document.getElementById('page1').style.backgroundSize="cover";
img2.onLoad=img2Loaded();
img2.src='img/bg2.jpg';
}
function img2Loaded(){
console.log('image2 loaded');
window.document.getElementById('page2').style.background= ' #009ee3 url(img/bg2.jpg) no-repeat center top';
window.document.getElementById('page2').style.backgroundSize="cover";
}
The console messages :
image1 loaded
image2 loaded
appear in the right order but almost at the same time. After a few seconds, both images are displayed at the same time.
What's wrong with my solution and how should I do ?
Upvotes: 1
Views: 3662
Reputation: 328604
Modern web browsers rarely open only a single connection. After the HTML has downloaded, all resources will be collected and the browser will load many of them in parallel. This is why your approach probably doesn't help a lot.
The timing you see can have many reasons. The most common of them is that you have opened this page before and you still had the images in the cache. The browser will then emit a small HEAD request which allows it to determine whether the image in the cache is still "good enough".
Try again with your caches flushed.
EDIT As devnull69 said, you have two severe bugs in the code:
onLoad
has no effect; the event handler is called onload
.img1.onload=img1Loaded
instead.Without these two bug fixes, the code above will:
img1Loaded();
which prints image1 loaded
img2Loaded();
which prints image2 loaded
img2.src
(loading the second image). This will actually trigger the loading after the script has returned.img1.src
(loading the first image, probably in parallel with the other one)Upvotes: 2