Controlling image load order in HTML

后端 未结 4 1049
别跟我提以往
别跟我提以往 2020-11-29 06:29

Is there a way to control the load order of images on a web page? I was thinking of trying to simulate a preloader by first loading a light-weight \'LOADING\' graphic. Any

4条回答
  •  自闭症患者
    2020-11-29 07:15

    Use Javascript, and populate the image src properties later. The # tells the browser to link to a URL on the page, so no request will be sent to the server. (If the src property was empty, a request is still made to the server - not great.)

    Assemble an array of image addresses, and recurse through it, loading your images and calling a recursive function when the onload or onerror method for each image returns a value.

    HTML:

    []
    []
    []
    

    JS:

    var imgAddresses = ['img1.png','img2.jpg','img3.gif'];
    
    function loadImage(counter) {
      // Break out if no more images
      if (counter==imgAddresses.length) { return; }
    
      // Grab an image obj
      var I = document.getElementById("img"+counter);
    
      // Monitor load or error events, moving on to next image in either case
      I.onload = I.onerror = function() { loadImage(counter+1); }
    
      //Change source (then wait for event)
      I.src = imgAddresses[counter];
    }
    
    loadImage(0);
    

    You could even play around with a document.getElementsByTagName("IMG").

    By the way, if you need a loading image, this is a good place to start.

    EDIT

    To avoid multiple requests to the server, you could use almost the same method, only don't insert image elements until you're ready to load them. Have a container waiting for each image. Then, loop through, get the span object, and dynamically insert the image tag:

    var img = document.createElement("IMG");
    document.getElementById('mySpan').appendChild(img);
    img.src = ...
    

    Then the image request is made only once, when the element is created.

提交回复
热议问题