简体   繁体   中英

How to load images in a predefined order with HTML/javascript?

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 ?

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:

  1. Setting onLoad has no effect; the event handler is called onload .
  2. Instead of assigning a function reference, you actually call the function. Use img1.onload=img1Loaded instead.

Without these two bug fixes, the code above will:

  1. Call img1Loaded(); which prints image1 loaded
  2. Call img2Loaded(); which prints image2 loaded
  3. Assign img2.src (loading the second image). This will actually trigger the loading after the script has returned.
  4. Assign img1.src (loading the first image, probably in parallel with the other one)

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